using System.Security.Claims;
using Baya.Domain.Entities.User;
using Baya.Infrastructure.Identity.Identity.PermissionManager;

namespace Baya.Test.Infrastructure.Identity
{
    public class DynamicPermissionServiceTest
    {
        private readonly DynamicPermissionService _sut = new();

        [Fact]
        public void Admin_Role_Bypasses_Permission_Check()
        {
            var user = BuildUser(RoleNames.Admin);

            Assert.True(_sut.CanAccess(user, area: null, controller: "AdminRefunds", action: "Create"));
        }

        [Fact]
        public void SuperAdmin_Role_Bypasses_Permission_Check()
        {
            var user = BuildUser(RoleNames.SuperAdmin);

            Assert.True(_sut.CanAccess(user, area: null, controller: "AdminRefunds", action: "Create"));
        }

        [Fact]
        public void Role_With_Matching_Claim_Is_Granted_Access()
        {
            var user = BuildUser(RoleNames.Finance, dynamicPermission: ":AdminRefunds:");

            Assert.True(_sut.CanAccess(user, area: null, controller: "AdminRefunds", action: "Create"));
        }

        [Fact]
        public void Role_Without_Matching_Claim_Is_Denied_Access()
        {
            var user = BuildUser(RoleNames.Finance, dynamicPermission: ":AdminRefunds:");

            Assert.False(_sut.CanAccess(user, area: null, controller: "AdminReviews", action: "Status"));
        }

        private static ClaimsPrincipal BuildUser(string role, string? dynamicPermission = null)
        {
            var claims = new List<Claim> { new(ClaimTypes.Role, role) };

            if (dynamicPermission != null)
                claims.Add(new Claim(ConstantPolicies.DynamicPermission, dynamicPermission));

            var identity = new ClaimsIdentity(claims, "TestAuth", ClaimTypes.Name, ClaimTypes.Role);
            return new ClaimsPrincipal(identity);
        }
    }
}
