using Microsoft.AspNetCore.Authentication.Negotiate;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using RIIT.Components;
using RIIT.Components.Account;
using RIIT.Data;

var builder = WebApplication.CreateBuilder(args);

// ===== Přepínač režimu (appsettings.json: "Auth:Mode": "Windows" | "Internal") =====
var authMode = builder.Configuration["Auth:Mode"]?.Trim() ?? "Internal";
var windowsEnabled = string.Equals(authMode, "Windows", StringComparison.OrdinalIgnoreCase);

if (windowsEnabled)
{
    // ? Negotiate v aplikaci (Kestrel) – POZOR: nepoužívej za IIS s Windows Auth!
    builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
                    .AddNegotiate();

    // Vyžaduj přihlášení všude (Fallback = Default)
    builder.Services.AddAuthorization(options =>
    {
        options.FallbackPolicy = options.DefaultPolicy;
    });
}
else
{
    // ? Interní Identity účty (cookies)
    builder.Services.AddScoped<IdentityRedirectManager>();
    builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();
    builder.Services.AddAuthentication(options =>
    {
        options.DefaultScheme = IdentityConstants.ApplicationScheme;
        options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
    })
    .AddIdentityCookies();

    builder.Services.AddAuthorization();

    builder.Services.AddIdentityCore<ApplicationUser>(options =>
    {
        options.SignIn.RequireConfirmedAccount = true;
        options.Stores.SchemaVersion = IdentitySchemaVersions.Version3;
    })
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddSignInManager()
        .AddDefaultTokenProviders();
}

// DB
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
    ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(o => o.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

// Email (no-op)
builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>();

// Blazor (server interaktivně) + cascading auth state (AuthorizeView apod.)
builder.Services.AddRazorComponents()
                .AddInteractiveServerComponents();
builder.Services.AddCascadingAuthenticationState(); 

var app = builder.Build();

// ------ Pipeline ------
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();

app.MapStaticAssets();
app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

// Add additional endpoints required by the Identity /Account Razor components.

if (!windowsEnabled)
{
    app.MapAdditionalIdentityEndpoints();
}
/*
// ? StatusCodePages: nikdy nesahat do 401/403 (kvůli Negotiate handshaku)
app.UseStatusCodePages(async context =>
{
    var code = context.HttpContext.Response.StatusCode;

    // Negotiate/Identity challenge – nesahej na to
    if (code == 401 || code == 403) return;

    // 404 apod. klidně přesměruj
    context.HttpContext.Response.Redirect("/not-found");
});

if (windowsEnabled)
{
    // FallbackPolicy už vyžaduje auth – tady .RequireAuthorization() není nutné
    app.MapRazorComponents<App>()
       .AddInteractiveServerRenderMode();
}
else
{
    // Interní účty: výslovně zamknout UI
    app.MapRazorComponents<App>()
       .AddInteractiveServerRenderMode()
       .RequireAuthorization();
}
*/
app.Run();