using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using planli.frontend;
using planli.frontend.Services;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

// ── API base URL ─────────────────────────────────────────────────────────────
// In production (Docker) ApiBaseUrl is absent → fall back to the app's own origin
// so all /api/* requests route through Traefik on the same host.
var apiBaseUrl = builder.Configuration["ApiBaseUrl"];
var apiBase = new Uri(string.IsNullOrWhiteSpace(apiBaseUrl)
    ? builder.HostEnvironment.BaseAddress
    : apiBaseUrl);

// ── Shared plain HttpClient ──────────────────────────────────────────────────
// Cookie-aware (credentials: include) but no retry / refresh logic.
// Used by RefreshService and PlanliAuthStateProvider to call /api/Auth/* endpoints
// without risking circular dependencies through AuthHttpHandler.
var plainClient = new HttpClient(
    new CookieHandler { InnerHandler = new HttpClientHandler() })
{
    BaseAddress = apiBase
};

// ── Auth services ────────────────────────────────────────────────────────────
builder.Services.AddAuthorizationCore();

builder.Services.AddScoped<RefreshService>(_ => new RefreshService(plainClient));

builder.Services.AddScoped<PlanliAuthStateProvider>(sp =>
    new PlanliAuthStateProvider(plainClient, sp.GetRequiredService<RefreshService>()));

builder.Services.AddScoped<AuthenticationStateProvider>(sp =>
    sp.GetRequiredService<PlanliAuthStateProvider>());

// ── Authenticated HttpClient (used by all pages) ─────────────────────────────
// Chain: AuthHttpHandler → CookieHandler → HttpClientHandler
builder.Services.AddScoped(sp =>
{
    var handler = new AuthHttpHandler(
        sp.GetRequiredService<RefreshService>(),
        sp.GetRequiredService<PlanliAuthStateProvider>())
    {
        InnerHandler = new CookieHandler { InnerHandler = new HttpClientHandler() }
    };
    return new HttpClient(handler) { BaseAddress = apiBase };
});

await builder.Build().RunAsync();
