using Microsoft.Extensions.DependencyInjection;
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>();

        // Configure named HttpClient with logging handler
        services.AddHttpClient("DiunaBI", client =>
        {
            client.BaseAddress = new Uri(baseUri);
            Console.WriteLine($"✅ HttpClient BaseAddress set to: {client.BaseAddress}");
        })
        .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<AuthService>();
        services.AddScoped<LayerService>();

        return services;
    }
}