using Blazored.LocalStorage;

namespace NetinaShop.AdminPanel.PWA.Utilities;

public class UserUtility : IUserUtility
{
    private readonly ILocalStorageService _localStorageService;

    public UserUtility(ILocalStorageService localStorageService)
    {
        _localStorageService = localStorageService;
    }

    public async Task<string> GetBearerTokenAsync() => await _localStorageService.GetItemAsStringAsync(LocalStorageKeys.Token);
    public async Task SetBearerTokenAsync(string token) => await _localStorageService.SetItemAsStringAsync(LocalStorageKeys.Token, token);

    public async Task<ApplicationUserSDto> GetUserAsync() => await _localStorageService.GetItemAsync<ApplicationUserSDto>(LocalStorageKeys.UserInfo);
    public async Task SetUserAsync(ApplicationUserSDto user) => await _localStorageService.SetItemAsync<ApplicationUserSDto>(LocalStorageKeys.UserInfo, user);
    public async Task SetPermissionsAsync(List<string> permissions) => await _localStorageService.SetItemAsync(LocalStorageKeys.UserPermissions,permissions);
    public async Task<List<string>> GetPermissionsAsync() => await _localStorageService.GetItemAsync<List<string>>(LocalStorageKeys.UserPermissions);


    public async Task<bool> HasPermissionAsync(string permission)
    {
        var permissions = await _localStorageService.GetItemAsync<List<string>>(LocalStorageKeys.UserPermissions);
        return permissions.Exists(p => p == permission);
    }

    public async Task LogoutAsync()
    {
        await _localStorageService.RemoveItemAsync(LocalStorageKeys.Token);
        await _localStorageService.RemoveItemAsync(LocalStorageKeys.UserInfo);
        await _localStorageService.RemoveItemAsync(LocalStorageKeys.UserPermissions);
    }

    //public AccessToken<ApplicationUserSDto>? AccessToken { get; set; }
    //public List<string> UserClaims => AccessToken == null ? new List<string>() : AccessToken.Permissions;
    //public bool HasPermissionTo(string permission) => UserClaims.Any(c => c == permission);
}