using Duende.IdentityServer.Models;
using Duende.IdentityServer.Services;
using LiteCharmsSecurity.Admin.EntityFramework.Shared.Entities.Identity;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;

namespace LiteCharmsSecurity.STS.Identity.Services;

public sealed class ClaimsInjectorProfileService(UserManager<UserIdentity> userManager) : IProfileService
{
    public Task GetProfileDataAsync(ProfileDataRequestContext context)
        => GetProfileDataAsync(context, CancellationToken.None);

    public async Task GetProfileDataAsync(ProfileDataRequestContext context, CancellationToken ct)
    {
        var user = await userManager.GetUserAsync(context.Subject);
        if (user != null && !string.IsNullOrEmpty(user.Email))
        {
            context.IssuedClaims.Add(new Claim("email", user.Email));
            context.IssuedClaims.Add(new Claim("email_verified", user.EmailConfirmed ? "true" : "false"));

            if (!string.IsNullOrEmpty(user.UserName))
            {
                context.IssuedClaims.Add(new Claim("preferred_username", user.UserName));
            }
        }
    }

    public Task IsActiveAsync(IsActiveContext context)
        => IsActiveAsync(context, CancellationToken.None);

    public async Task IsActiveAsync(IsActiveContext context, CancellationToken ct)
    {
        var user = await userManager.GetUserAsync(context.Subject);
        context.IsActive = user != null;
    }
}