using System.Security.Claims;
using Baya.Domain.Entities.User;

namespace Baya.Infrastructure.Identity.Identity.PermissionManager;

public class DynamicPermissionService : IDynamicPermissionService
{
    public bool CanAccess(ClaimsPrincipal user, string area, string controller, string action)
    {
        // super_admin is definitionally the top role, but RoleNames has no hierarchy — each admin
        // sub-role is a sibling, so it must be granted the bypass explicitly, not implied by "admin".
        if (user.IsInRole(RoleNames.Admin) || user.IsInRole(RoleNames.SuperAdmin))
        {
            return true;
        }

        var key = $"{area}:{controller}:";

        var userClaims = user.FindAll(ConstantPolicies.DynamicPermission);

        return userClaims.Any(item => item.Value.Equals(key, StringComparison.OrdinalIgnoreCase));
    }
}