using Blazored.LocalStorage;
using NetinaShop.AdminPanel.PWA.Extensions;

namespace NetinaShop.AdminPanel.PWA.Utilities;

public class UserUtility : IUserUtility
{
    private readonly ILocalStorageService _localStorageService;
    private readonly IEncryptProvider _encryptProvider;

    public UserUtility(ILocalStorageService localStorageService,IEncryptProvider encryptProvider)
    {
        _localStorageService = localStorageService;
        _encryptProvider = encryptProvider;
    }

    public async Task<string?> GetBearerTokenAsync()
    {
        var encrypted = await _localStorageService.GetItemAsStringAsync(LocalStorageKeys.Token);
        return await _encryptProvider.Decrypt<string>(encrypted);
    }

    public async Task SetBearerTokenAsync(string token)
    {
        var encrypted = await _encryptProvider.Encrypt<string>(token);
        await _localStorageService.SetItemAsStringAsync(LocalStorageKeys.Token, encrypted);
    }

    public async Task<ApplicationUserSDto?> GetUserAsync()
    {
        var encryptedUser = await _localStorageService.GetItemAsync<string>(LocalStorageKeys.UserInfo);
        return await _encryptProvider.Decrypt<ApplicationUserSDto>(encryptedUser);
    }

    public async Task SetUserAsync(ApplicationUserSDto user)
    {
        var encryptedUser = await _encryptProvider.Encrypt(user);
        await _localStorageService.SetItemAsync(LocalStorageKeys.UserInfo, encryptedUser);
    }

    public async Task SetPermissionsAsync(List<string> permissions)
    {
        var encrypted = await _encryptProvider.Encrypt(permissions);
        await _localStorageService.SetItemAsync(LocalStorageKeys.UserPermissions,encrypted);
    }

    public async Task<List<string>?> GetPermissionsAsync()
    {
        var encrypted = await _localStorageService.GetItemAsync<string>(LocalStorageKeys.UserPermissions);
        return await _encryptProvider.Decrypt<List<string>>(encrypted);
    }


    public async Task<bool> HasPermissionAsync(string permission)
    {
        var permissions = await GetPermissionsAsync();
        if (permissions == null)
            return false;
        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);
}