using Microsoft.AspNetCore.Authorization;
using ROLAC.API.Services;

namespace ROLAC.API.Authorization;

/// <summary>
/// Evaluates <see cref="PermissionRequirement"/> against the user's roles.
/// <c>super_admin</c> always passes (bypass); otherwise the requirement succeeds if
/// ANY of the user's roles grants the requested module/action (union across roles).
/// </summary>
public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionRequirement>
{
    public const string SuperAdminRole = "super_admin";

    private readonly IPermissionService _permissions;

    public PermissionAuthorizationHandler(IPermissionService permissions)
        => _permissions = permissions;

    protected override async Task HandleRequirementAsync(
        AuthorizationHandlerContext context, PermissionRequirement requirement)
    {
        // Roles live in "role" claims (RoleClaimType = "role", MapInboundClaims = false).
        var roles = context.User.FindAll("role").Select(claim => claim.Value).ToList();

        if (roles.Contains(SuperAdminRole))
        {
            context.Succeed(requirement);
            return;
        }

        if (await _permissions.HasPermissionAsync(roles, requirement.Module, requirement.Action))
            context.Succeed(requirement);
    }
}
