using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.DependencyInjection;
using DiunaBI.UI.Shared.Services;

namespace DiunaBI.UI.Shared.Handlers;

public class UnauthorizedResponseHandler : DelegatingHandler
{
    private readonly IServiceProvider _serviceProvider;

    public UnauthorizedResponseHandler(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        // Check if response is 401 Unauthorized
        if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
        {
            Console.WriteLine("⚠️ 401 Unauthorized response detected - clearing credentials and redirecting to login");

            // Create a scope to get scoped services
            using var scope = _serviceProvider.CreateScope();
            var authService = scope.ServiceProvider.GetRequiredService<AuthService>();
            var navigationManager = scope.ServiceProvider.GetRequiredService<NavigationManager>();

            // Clear authentication
            await authService.ClearAuthenticationAsync();

            // Navigate to login page with session expired message
            navigationManager.NavigateTo("/login?sessionExpired=true", forceLoad: true);
        }

        return response;
    }
}
