using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection; // 需要这个命名空间来获取 IServiceProvider
using System; // 需要这个命名空间来使用 Lazy<T>

namespace TechHelper.Client.HttpRepository
{
	public class RefreshTokenService : IRefreshTokenService
	{

		private readonly Lazy<AuthenticationStateProvider> _authenticationStateProvider;
		private readonly Lazy<IAuthenticationClientService> _authenticationClientService;

		public RefreshTokenService(IServiceProvider serviceProvider)
		{
			_authenticationStateProvider = new Lazy<AuthenticationStateProvider>(
				() => serviceProvider.GetRequiredService<AuthenticationStateProvider>());

			_authenticationClientService = new Lazy<IAuthenticationClientService>(
				() => serviceProvider.GetRequiredService<IAuthenticationClientService>());
		}

		public async Task<string> TryRefreshToken()
		{
			var authState = await _authenticationStateProvider.Value.GetAuthenticationStateAsync();
			var user = authState.User;

			if (user?.Identity == null || !user.Identity.IsAuthenticated)
			{
				return string.Empty;
			}

			var expClaim = user.FindFirst(c => c.Type.Equals("exp"))?.Value; 
			if (string.IsNullOrEmpty(expClaim))
			{
				return string.Empty; 
			}

			var expTime = DateTimeOffset.FromUnixTimeSeconds(
				Convert.ToInt64(expClaim));

			var diff = expTime - DateTime.UtcNow;


			var n = DateTime.UtcNow;

			if (diff.TotalMinutes <= 2)
				return await _authenticationClientService.Value.RefreshTokenAsync(); 

			return string.Empty;
		}
	}
}