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

namespace DiunaBI.UI.Shared.Extensions;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddSharedServices(this IServiceCollection services, string apiBaseUrl)
    {
        // HttpClient for API calls with logging
        // Ensure BaseAddress ends with / for proper relative URL resolution
        var baseUri = apiBaseUrl.EndsWith('/') ? apiBaseUrl : apiBaseUrl + "/";

        Console.WriteLine($"🔧 Configuring HttpClient with BaseAddress: {baseUri}");

        services.AddTransient<HttpLoggingHandler>();
        services.AddTransient<UnauthorizedResponseHandler>();

        // Configure named HttpClient with logging and 401 handling
        // Note: Authentication is handled by AuthService setting DefaultRequestHeaders.Authorization
        services.AddHttpClient("DiunaBI", client =>
        {
            client.BaseAddress = new Uri(baseUri);
            Console.WriteLine($"✅ HttpClient BaseAddress set to: {client.BaseAddress}");
        })
        .AddHttpMessageHandler<UnauthorizedResponseHandler>()
        .AddHttpMessageHandler<HttpLoggingHandler>();

        // Register a scoped HttpClient factory that services will use
        services.AddScoped<HttpClient>(sp =>
        {
            var factory = sp.GetRequiredService<IHttpClientFactory>();
            var client = factory.CreateClient("DiunaBI");
            Console.WriteLine($"🏭 HttpClient created from factory. BaseAddress: {client.BaseAddress}");
            return client;
        });

        // Services
        services.AddScoped<TokenProvider>();
        services.AddScoped<AuthService>();
        services.AddScoped<LayerService>();
        services.AddScoped<DataInboxService>();
        services.AddScoped<JobService>();
        services.AddScoped<DateTimeHelper>();
        services.AddScoped<NumberFormatHelper>();

        // Filter state services (scoped to maintain state during user session)
        services.AddScoped<LayerFilterStateService>();
        services.AddScoped<DataInboxFilterStateService>();

        // SignalR Hub Service (scoped per user session for authenticated connections)
        services.AddScoped(sp =>
        {
            var logger = sp.GetRequiredService<ILogger<EntityChangeHubService>>();
            var tokenProvider = sp.GetRequiredService<TokenProvider>();
            return new EntityChangeHubService(apiBaseUrl, sp, logger, tokenProvider);
        });

        return services;
    }
}