using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;

namespace Ladaer.BackEnd.Infrastructures.Authorization
{
    /// <summary>
    /// Custom Authorization Handler cho phép Founder bypass tất cả role checks
    /// </summary>
    public class FounderBypassAuthorizationHandler : IAuthorizationHandler
    {
        private readonly ILogger<FounderBypassAuthorizationHandler> _logger;

        public FounderBypassAuthorizationHandler(ILogger<FounderBypassAuthorizationHandler> logger)
        {
            _logger = logger;
        }

        public Task HandleAsync(AuthorizationHandlerContext context)
        {
            // Kiểm tra nếu user đã authenticated
            if (!context.User.Identity?.IsAuthenticated ?? true)
            {
                return Task.CompletedTask;
            }

            // Kiểm tra nếu user có role "Founder"
            if (context.User.IsInRole("Founder"))
            {
                _logger.LogInformation("Founder access granted for user: {UserId} to resource: {Resource}", 
                    context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value,
                    context.Resource?.ToString() ?? "Unknown");

                // Founder được phép truy cập tất cả - mark tất cả requirements là succeeded
                foreach (var requirement in context.Requirements)
                {
                    if (!context.HasSucceeded)
                    {
                        context.Succeed(requirement);
                    }
                }
            }

            return Task.CompletedTask;
        }
    }
}
