using Microsoft.AspNetCore.Components;

namespace Atomx.Admin.Client.Utils
{
    public class AuthHeaderHandler : DelegatingHandler
    {
        private readonly ITokenProvider _tokenProvider;
        private readonly NavigationManager _navigationManager;
        private readonly ILogger<AuthHeaderHandler> _logger;

        public AuthHeaderHandler(
            ITokenProvider tokenProvider,
            NavigationManager navigationManager,
            ILogger<AuthHeaderHandler> logger)
        {
            _tokenProvider = tokenProvider;
            _navigationManager = navigationManager;
            _logger = logger;
        }

        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取token
                var token = await _tokenProvider.GetTokenAsync();

                if (!string.IsNullOrEmpty(token))
                {
                    request.Headers.Authorization =
                        new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                }
                else
                {
                    _logger.LogWarning("No authentication token available for request: {Url}", request.RequestUri);
                }

                var response = await base.SendAsync(request, cancellationToken);

                // 处理认证失败
                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    await HandleUnauthorizedAsync();
                }

                return response;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error sending HTTP request to {Url}", request.RequestUri);
                throw;
            }
        }

        private async Task HandleUnauthorizedAsync()
        {
            // 在WASM模式下重定向到登录页
            if (OperatingSystem.IsBrowser())
            {
                _navigationManager.NavigateTo("/account/login", true);
            }
            // 在Server模式下可以执行其他操作
            else
            {
                // Server端的处理逻辑
                _logger.LogWarning("Unauthorized access detected in server mode");
            }
        }
    }
}