using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Nalu.Web.Data.Repositories;
using Stripe.Checkout;

namespace Nalu.Web.Pages.Precos;

public class SucessoModel(
    UserRepository users,
    SubscriptionRepository subscriptions,
    ILogger<SucessoModel> logger) : PageModel
{
    public string? PlanName { get; private set; }
    public bool Applied { get; private set; }

    public async Task<IActionResult> OnGetAsync(string? session_id, CancellationToken ct)
    {
        if (string.IsNullOrEmpty(session_id))
            return RedirectToPage("/Precos/Index");

        try
        {
            var service = new SessionService();
            var session = await service.GetAsync(session_id, cancellationToken: ct);

            var userId = session.Metadata?.GetValueOrDefault("user_id");
            var plan   = session.Metadata?.GetValueOrDefault("plan");

            if (!string.IsNullOrEmpty(userId) && !string.IsNullOrEmpty(plan)
                && session.PaymentStatus == "paid")
            {
                await users.UpdatePlanAsync(userId, plan, ct);

                if (!string.IsNullOrEmpty(session.CustomerId))
                    await users.SetStripeCustomerAsync(userId, session.CustomerId, ct);

                // Upsert subscription so dashboard reflects it even before webhook arrives
                var stripeSubId = session.SubscriptionId;
                if (!string.IsNullOrEmpty(stripeSubId))
                {
                    var existing = await subscriptions.FindByStripeIdAsync(stripeSubId, ct);
                    if (existing == null)
                    {
                        await subscriptions.UpsertAsync(new Nalu.Web.Data.Models.Subscription
                        {
                            UserId               = userId,
                            StripeSubscriptionId = stripeSubId,
                            StripeCustomerId     = session.CustomerId ?? "",
                            Plan                 = plan,
                            Status               = "active",
                            CurrentPeriodStart   = session.Created,
                            CurrentPeriodEnd     = session.Created.AddMonths(1),
                        }, ct);
                    }
                }

                PlanName = plan;
                Applied  = true;
                logger.LogInformation("Success page applied plan {Plan} to user {UserId}", plan, userId);
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Error applying plan on success page for session {SessionId}", session_id);
        }

        return Page();
    }
}
