using Blazored.LocalStorage;
using Blazored.Modal;
using Blazored.Toast;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Options;
using ReAct_PME.WebUI;
using ReAct_PME.WebUI.ServicesUI;


var builder = WebAssemblyHostBuilder.CreateDefault(args);

// Composants Blazor
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

// Blazored
builder.Services.AddBlazoredModal();
builder.Services.AddBlazoredToast();
builder.Services.AddBlazoredLocalStorage();

// Authentification
builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();
builder.Services.AddAuthorizationCore();

// Chargement dynamique de config JSON
var http = new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) };

// Charge appsettings.json
using var baseStream = await http.GetStreamAsync("appsettings.json");
var configBuilder = new ConfigurationBuilder().AddJsonStream(baseStream);

// Charge aussi appsettings.Development.json si applicable
if (builder.HostEnvironment.IsDevelopment())
{
    var devStream  = await http.GetStreamAsync("appsettings.Development.json");
    configBuilder.AddJsonStream(devStream);
}

// Charge aussi appsettings.Production.json si applicable
if (builder.HostEnvironment.IsProduction())
{
    var prodStream = await http.GetStreamAsync("appsettings.Production.json");
    configBuilder.AddJsonStream(prodStream);
}

// Injecte la configuration
var config = configBuilder.Build();
builder.Configuration.AddConfiguration(config);

// Bind les sections "ApiBaseUrls" et "ApiJwtBaseUrls"
builder.Services.Configure<ApiBaseUrls>(config.GetSection("ApiBaseUrls"));
builder.Services.Configure<ApiJwtBaseUrls>(config.GetSection("ApiJwtBaseUrls"));

// DÉTECTION dynamique : IP locale => Local, sinon => Remote
builder.Services.Configure<ApiSettings>(options =>
{
    var apiUrls = config.GetSection("ApiBaseUrls").Get<ApiBaseUrls>();
    var jwtUrls = config.GetSection("ApiJwtBaseUrls").Get<ApiJwtBaseUrls>();

    var baseAddress = new Uri(builder.HostEnvironment.BaseAddress);
    var host = baseAddress.Host;

    bool isLocal = host.StartsWith("localhost") || host.StartsWith("192.168.") || host.StartsWith("127.0.0.1");

    options.ApiBaseUrl = isLocal ? apiUrls!.Local : apiUrls!.Remote;
    options.ApiJwtBaseUrl = isLocal ? jwtUrls!.Local : jwtUrls!.Remote;
});

// HttpClient
builder.Services.AddScoped(sp =>
{
    var settings = sp.GetRequiredService<IOptions<ApiSettings>>().Value;
    return new HttpClient { BaseAddress = new Uri(settings.ApiBaseUrl) };
});

// Auth handler
builder.Services.AddTransient<AuthorizedHttpClientHandler>();

// HttpClient JWT
builder.Services.AddHttpClient<ApiService>((sp, client) =>
{
    var settings = sp.GetRequiredService<IOptions<ApiSettings>>().Value;
    client.BaseAddress = new Uri(settings.ApiBaseUrl);
}).AddHttpMessageHandler<AuthorizedHttpClientHandler>();

// Variante manuelle
builder.Services.AddScoped(sp =>
{
    var settings = sp.GetRequiredService<IOptions<ApiSettings>>().Value;
    var handler = sp.GetRequiredService<AuthorizedHttpClientHandler>();
    handler.InnerHandler = new HttpClientHandler();

    return new HttpClient(handler)
    {
        BaseAddress = new Uri(settings.ApiBaseUrl)
    };
});

await builder.Build().RunAsync();          
