using Atomx.Common.Configuration;
using Microsoft.JSInterop;

namespace Atomx.Admin.Client.Utils
{
    public interface ITokenProvider
    {
        Task<string?> GetTokenAsync();
        Task<bool> IsTokenValidAsync();
    }

    public class ClientTokenProvider : ITokenProvider
    {
        private readonly IJSRuntime _jsRuntime;

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

        public async Task<string?> GetTokenAsync()
        {
            try
            {
                // 从localStorage或sessionStorage获取token
                return await _jsRuntime.InvokeAsync<string>("localStorage.getItem", StorageKeys.JWTTokenKeyName);
            }
            catch
            {
                return null;
            }
        }

        public async Task<bool> IsTokenValidAsync()
        {
            var token = await GetTokenAsync();
            return !string.IsNullOrEmpty(token);
        }
    }
}
