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

namespace FJPSite.Handlers;

public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionRequirement>
{
    private readonly IPermissionService _permissionService;
    private readonly IHttpContextAccessor _httpContextAccessor;
    public PermissionAuthorizationHandler(
     IPermissionService permissionService,
     IHttpContextAccessor httpContextAccessor)
    {
        _permissionService = permissionService;
        _httpContextAccessor = httpContextAccessor;
    }
    protected override async Task HandleRequirementAsync(
     AuthorizationHandlerContext context,
     PermissionRequirement requirement)
    {
        if (context.User == null)
        {
            context.Fail();
            return;
        }
        // Get user ID from claims
        var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        if (string.IsNullOrEmpty(userId))
        {
            context.Fail();
            return;
        }
        // Check if user has the required permission
        bool hasPermission = await _permissionService
        .UserHasPermissionAsync(userId, requirement.Feature, requirement.Action);
        if (hasPermission)
        {
            context.Succeed(requirement);
        }
        else
        {
            context.Fail();
        }
    }