using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;

namespace NetinaShop.AdminPanel.PWA.Services;

public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
    private readonly IUserUtility _userUtility;

    public CustomAuthenticationStateProvider(IUserUtility userUtility)
    {
        _userUtility = userUtility;
    }
    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {

        var token = await _userUtility.GetBearerTokenAsync();
        if (token.IsNullOrEmpty())
            return new AuthenticationState(new());

        var user = await _userUtility.GetUserAsync();
        if (user == null)
            return new AuthenticationState(new());
        if (user.RoleName == "Customer")
            return new AuthenticationState(new());
        var permissions = await _userUtility.GetPermissionsAsync();
        
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, user.FirstName + " " + user.LastName),
            new Claim(ClaimTypes.MobilePhone, user.PhoneNumber),
            new Claim(ClaimTypes.Role,user.RoleName)
        };
        if (permissions != null)
            permissions.ForEach(p => claims.Add(new Claim("Permission", p)));
        var identity = new ClaimsIdentity(claims, "Bearer");

        var claimUser = new ClaimsPrincipal(identity);


        return new AuthenticationState(claimUser);
    }
}