namespace MyOffice.Web.Auth;

using System.Security.Claims;
using Identity.Domain;
using Microsoft.IdentityModel.Tokens;
using OpenIddict.Abstractions;
using static OpenIddict.Abstractions.OpenIddictConstants;

public static class OpenIddictClaimsHelper
{
	public static ClaimsPrincipal CreatePrincipal(
		ApplicationUser<Guid> user,
		IEnumerable<string> scopes
	)
	{
		var identity = new ClaimsIdentity(
			authenticationType: TokenValidationParameters.DefaultAuthenticationType,
			nameType: Claims.Name,
			roleType: Claims.Role);

		var userId = user.Id.ToString();
		identity.SetClaim(Claims.Subject, userId);
		identity.SetClaim(Claims.Name, user.UserName);
		identity.SetClaim(Claims.PreferredUsername, user.UserName);
		identity.SetClaim(Claims.Email, user.Email);
		identity.SetClaim(Claims.EmailVerified, user.IsEmailConfirmed);

		if (!string.IsNullOrWhiteSpace(user.FullName))
			identity.SetClaim(Claims.GivenName, user.FullName);

		identity.SetScopes(scopes);
		identity.SetDestinations(static claim => claim.Type switch
		{
			Claims.Name or Claims.PreferredUsername or Claims.Email or Claims.EmailVerified or Claims.GivenName
				=> [Destinations.AccessToken, Destinations.IdentityToken],
			_ => [Destinations.AccessToken]
		});

		return new ClaimsPrincipal(identity);
	}
}
