using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using MongoDB.Driver;
using Nalu.Web.Data;
using Nalu.Web.Data.Models;
using Nalu.Web.Data.Repositories;
using Nalu.Web.Services;

namespace Nalu.Web.Pages.Painel;

[Authorize]
public class IndexModel(
    ApiKeyRepository apiKeys,
    MongoDbContext db,
    IConfiguration config) : PageModel
{
    public List<ApiKey> Keys { get; private set; } = [];
    public int CreditsUsed { get; private set; }
    public int CreditsLimit { get; private set; }
    public string? NewApiKey { get; private set; }
    public string UserName { get; private set; } = "";
    public string UserEmail { get; private set; } = "";
    public string UserPicture { get; private set; } = "";
    public string Plan { get; private set; } = "free";

    public async Task OnGetAsync(CancellationToken ct)
    {
        UserName = User.FindFirstValue(ClaimTypes.Name) ?? "";
        UserEmail = User.FindFirstValue(ClaimTypes.Email) ?? "";
        UserPicture = User.FindFirstValue("picture") ?? "";
        Plan = User.FindFirstValue("plan") ?? "free";

        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "";
        Keys = await apiKeys.GetByUserAsync(userId, ct);

        // Get credit usage from UsageMonthly (same collection CreditService writes to)
        if (Keys.Count > 0 && db.IsConnected)
        {
            var yearMonth = DateTime.UtcNow.ToString("yyyy-MM");
            var monthly = await db.UsageMonthly
                .Find(u => u.ApiKey == Keys[0].Key && u.YearMonth == yearMonth)
                .FirstOrDefaultAsync(ct);
            CreditsUsed = monthly?.TotalCreditsUsed ?? 0;
        }

        var planConfig = config.GetSection($"Plans:{Plan}");
        CreditsLimit = planConfig.GetValue<int>("credits_per_month");
        if (CreditsLimit == 0) CreditsLimit = 3000;

        // Welcome modal — shown once
        NewApiKey = TempData["NewApiKey"] as string;
    }

    public async Task<IActionResult> OnPostRevokeAsync(string key, CancellationToken ct)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "";
        var userKeys = await apiKeys.GetByUserAsync(userId, ct);

        // Only revoke keys owned by this user
        if (userKeys.Any(k => k.Key == key))
            await apiKeys.RevokeAsync(key, ct);

        return RedirectToPage();
    }
}
