using System.Security.Claims;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using TrackQrApi.Data;
using TrackQrApi.Features.Auth.Common;
using TrackQrApi.Features.Billing.Common;
using TrackQrApi.Features.Billing.Services;
using TrackQrApi.Models;

namespace TrackQrApi.Features.Billing.Endpoints;

public class GetSubscriptionRequest
{
    public Guid WorkspaceId { get; set; }
}

public class GetSubscriptionEndpoint(AppDbContext db, IStripeService stripeService)
    : Endpoint<GetSubscriptionRequest, SubscriptionResponse>
{
    public override void Configure()
    {
        Get("/workspaces/{WorkspaceId}/subscription");
    }

    public override async Task HandleAsync(GetSubscriptionRequest req, CancellationToken ct)
    {
        var userId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);

        var workspace = await db.Workspaces
            .FirstOrDefaultAsync(w => w.Id == req.WorkspaceId && w.OwnerUserId == userId, ct);

        if (workspace == null)
        {
            await HttpContext.Response.SendAsync(new MessageResponse("Workspace not found"), 404, cancellation: ct);
            return;
        }

        var isActive = workspace.Plan != WorkspacePlan.Free;
        var cancelAtPeriodEnd = false;

        // Get live subscription status from Stripe if exists
        if (!string.IsNullOrEmpty(workspace.StripeSubscriptionId))
        {
            var subscription = await stripeService.GetSubscriptionAsync(workspace.StripeSubscriptionId, ct);
            if (subscription != null)
            {
                isActive = subscription.Status == "active" || subscription.Status == "trialing";
                cancelAtPeriodEnd = subscription.CancelAtPeriodEnd;
            }
        }

        var response = new SubscriptionResponse(
            workspace.Id,
            workspace.Plan.ToString(),
            workspace.StripeSubscriptionId,
            workspace.SubscriptionEndsAt,
            isActive,
            cancelAtPeriodEnd
        );

        await HttpContext.Response.SendAsync(response, cancellation: ct);
    }
}