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

namespace PARR.API.RoleProvider
{
    public class SimpleRoleAuthorizationTransform : IClaimsTransformation
    {
        //private static readonly string RoleClaimType = $"http://{typeof(SimpleRoleAuthorizationTransform).FullName.Replace('.', '/')}/role";
        private static readonly string RoleClaimType = ClaimTypes.Role;

        private readonly ISimpleRoleProvider roleProvider;

        public SimpleRoleAuthorizationTransform(ISimpleRoleProvider roleProvider)
        {
            this.roleProvider = roleProvider ?? throw new ArgumentNullException(nameof(roleProvider));
        }

        public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            // Cast the principal identity to a Claims identity to access claims etc...
            var oldIdentity = (ClaimsIdentity)principal.Identity!;

            // "Clone" the old identity to avoid nasty side effects.
            // NB: We take a chance to replace the claim type used to define the roles with our own.
            var newIdentity = new ClaimsIdentity(
                oldIdentity.Claims,
                oldIdentity.AuthenticationType,
                oldIdentity.NameClaimType,
                RoleClaimType);

            // Fetch the roles for the user and add the claims of the correct type so that roles can be recognized.
            var roles = await roleProvider.GetUserRolesAsync(newIdentity.Name!);
            newIdentity.AddClaims(roles.Select(r => new Claim(RoleClaimType, r)));

            // Create and return a new claims principal
            return new ClaimsPrincipal(newIdentity);
        }
    }
}
