using Microsoft.AspNetCore.Components.Authorization;
using TecniStamp.Service.Interfaces;

namespace TecniStamp.Utils;

public static class MembershipUtils
{
    public static async Task<Guid> GetUserId(AuthenticationStateProvider auth)
    {
        var state = await auth.GetAuthenticationStateAsync();
        var idClaim = state.User.FindFirst("UserId")?.Value;

        return Guid.Parse(idClaim ?? Guid.Empty.ToString());
    }
    
    public static async Task<Guid> GetRoleId(AuthenticationStateProvider auth)
    {
        var state = await auth.GetAuthenticationStateAsync();
        var idClaim = state.User.FindFirst("RoleId")?.Value;

        return Guid.Parse(idClaim ?? Guid.Empty.ToString());
    }
    
    public static async Task<bool> CheckPermission(AuthenticationStateProvider auth, IManagerService managerService, string featureName)
    {
        var state = await auth.GetAuthenticationStateAsync();
        var idClaim = state.User.FindFirst("RoleId")?.Value;

        var parsed = Guid.Parse(idClaim ?? Guid.Empty.ToString());

        var perm = await managerService.RuoloService.RicercaPer(x =>
            x.Id == parsed && x.Permessi.Any(y => y.Feature.Nome == featureName && y.Eliminato == false) && x.Eliminato == false);
        return perm != null;
    }
}
