using Microsoft.JSInterop;

namespace TaxBaik.Web.Services;

public class LocalStorageService : ILocalStorageService
{
    private readonly IJSRuntime _jsRuntime;

    public LocalStorageService(IJSRuntime jsRuntime)
    {
        _jsRuntime = jsRuntime;
    }

    public async Task<string?> GetItemAsStringAsync(string key)
    {
        try
        {
            return await _jsRuntime.InvokeAsync<string>("taxbaikAdminSession.getLocalStorageItem", key);
        }
        catch
        {
            return null;
        }
    }

    public async Task SetItemAsStringAsync(string key, string value)
    {
        try
        {
            await _jsRuntime.InvokeVoidAsync("taxbaikAdminSession.setLocalStorageItem", key, value);
        }
        catch { }
    }

    public async Task RemoveItemAsync(string key)
    {
        try
        {
            await _jsRuntime.InvokeVoidAsync("taxbaikAdminSession.removeLocalStorageItem", key);
        }
        catch { }
    }

    public async Task ClearAuthAsync()
    {
        try
        {
            await RemoveItemAsync("accessToken");
            await RemoveItemAsync("refreshToken");
            await RemoveItemAsync("tokenExpiry");
            await RemoveItemAsync("auth_token");
            await RemoveItemAsync("admin-remembered-username");
        }
        catch { }
    }
}
