using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using NexusReader.Domain.Entities;
using Microsoft.EntityFrameworkCore;

using NexusReader.Data.Persistence;

namespace NexusReader.Application.Security.Authorization;

public class ProUserHandler : AuthorizationHandler<ProUserRequirement>
{
    private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
    
    public ProUserHandler(IDbContextFactory<AppDbContext> dbContextFactory)
    {
        _dbContextFactory = dbContextFactory;
    }

    protected override async Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        ProUserRequirement requirement)
    {
        var userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return;
        }

        using var db = _dbContextFactory.CreateDbContext();
        var user = await db.Users
            .Include(u => u.SubscriptionPlan)
            .FirstOrDefaultAsync(u => u.Id == userId);
            
        if (user == null)
        {
            return;
        }

        // Rule 1: Unlimited access
        if (user.SubscriptionPlan?.IsUnlimitedTokens == true)
        {
            context.Succeed(requirement);
            return;
        }

        // Rule 2: Within Token Limits (SaaS logic)
        if (user.AITokensUsed < user.AITokenLimit)
        {
            context.Succeed(requirement);
            return;
        }
    }
}
