using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Stripe.Checkout;

namespace Nalu.Web.Pages;

public class CheckoutModel(IConfiguration config, ILogger<CheckoutModel> logger) : PageModel
{
    private static readonly Dictionary<string, (string Name, string Description)> PlanMeta = new()
    {
        ["starter"] = ("NALU AI — Starter", "15.000 créditos/mês"),
        ["indie"]   = ("NALU AI — Indie",   "50.000 créditos/mês"),
        ["pro"]     = ("NALU AI — Pro",      "250.000 créditos/mês"),
    };

    public IActionResult OnGet(string plan)
    {
        if (!PlanMeta.ContainsKey(plan))
            return RedirectToPage("/Precos");

        if (!(User.Identity?.IsAuthenticated ?? false))
            return Redirect($"/login?returnUrl={Uri.EscapeDataString($"/checkout?plan={plan}")}");

        return Page();
    }

    public async Task<IActionResult> OnPostAsync(string plan)
    {
        if (!PlanMeta.ContainsKey(plan))
            return RedirectToPage("/Precos");

        if (!(User.Identity?.IsAuthenticated ?? false))
            return Redirect($"/login?returnUrl={Uri.EscapeDataString($"/checkout?plan={plan}")}");

        var priceBrl = config.GetValue<int>($"Plans:{plan}:price_brl");
        if (priceBrl <= 0)
        {
            TempData["CheckoutError"] = "Plano inválido ou sem preço configurado.";
            return RedirectToPage("/Precos");
        }

        var userId  = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "";
        var email   = User.FindFirstValue(ClaimTypes.Email) ?? "";
        var baseUrl = $"{Request.Scheme}://{Request.Host}";
        var meta    = PlanMeta[plan];

        var options = new SessionCreateOptions
        {
            Mode            = "subscription",
            CustomerEmail   = email,
            LineItems       =
            [
                new SessionLineItemOptions
                {
                    Quantity  = 1,
                    PriceData = new SessionLineItemPriceDataOptions
                    {
                        Currency   = "brl",
                        UnitAmount = (long)priceBrl,          // já em centavos no config (2900 = R$29)
                        Recurring  = new SessionLineItemPriceDataRecurringOptions
                        {
                            Interval = "month",
                        },
                        ProductData = new SessionLineItemPriceDataProductDataOptions
                        {
                            Name        = meta.Name,
                            Description = meta.Description,
                        },
                    },
                }
            ],
            Metadata = new Dictionary<string, string>
            {
                ["user_id"] = userId,
                ["plan"]    = plan,
            },
            SuccessUrl          = $"{baseUrl}/precos/sucesso?session_id={{CHECKOUT_SESSION_ID}}",
            CancelUrl           = $"{baseUrl}/precos",
            AllowPromotionCodes = true,
        };

        try
        {
            var service = new SessionService();
            var session = await service.CreateAsync(options);
            return Redirect(session.Url);
        }
        catch (Stripe.StripeException ex)
        {
            logger.LogError(ex, "Stripe checkout error for plan {Plan}", plan);
            TempData["CheckoutError"] = "Erro ao iniciar pagamento. Tente novamente.";
            return RedirectToPage("/Precos");
        }
    }
}
