using Nexus.Api.Extensions;
using Nexus.Api.Http;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);
var isOpenApiGeneration =
    Assembly.GetEntryAssembly()?.GetName().Name == "GetDocument.Insider";
if (isOpenApiGeneration)
{
    // The build-time mock host never accepts traffic. It still constructs the
    // auth services, so use an ephemeral contract-only signing value.
    builder.Configuration["Jwt:Key"] =
        "openapi-contract-generation-only-000000000000000000";
}

// --- Service Registration ---
builder.Services.AddNexusAuth(builder.Configuration);
builder.Services.AddNexusRateLimiting();
builder.Services.AddNexusForwardedHeaders(builder.Configuration);
builder.Services.AddNexusSwagger();
builder.Services.AddNexusDatabase(builder.Configuration);
builder.Services.AddNexusHttpClients(builder.Configuration);
builder.Services.AddNexusApplicationServices(
    includeHostedServices: !isOpenApiGeneration,
    includeMcp: !isOpenApiGeneration);
builder.Services.AddNexusRepositories();
builder.Services.AddNexusHealthChecks(builder.Configuration);
builder.Services.AddNexusPlatform(builder.Configuration);
builder.Services.AddControllers(options =>
    options.Filters.Add<NexusProblemDetailsFilter>());
if (isOpenApiGeneration)
{
    // Apply this after every framework service has registered its defaults.
    // The contract host never accepts traffic and must not persist runtime
    // key material as a side effect of schema extraction.
    builder.Services.AddDataProtection()
        .UseEphemeralDataProtectionProvider();
    builder.Services.PostConfigure<KeyManagementOptions>(options =>
        options.AutoGenerateKeys = false);
}

var app = builder.Build();

// Build-time OpenAPI extraction constructs the host without a database. The
// flag is supplied only by the project target; normal application starts keep
// the migration and seed gate mandatory.
if (!isOpenApiGeneration)
{
    // --- Database Migration & Seeding ---
    await app.EnsureDatabaseAsync();
}

// --- Middleware Pipeline ---
app.UseNexusPipeline(app.Environment);

if (!isOpenApiGeneration)
    app.MapMcp("/mcp");
app.MapOpenApi("/openapi/{documentName}.json");
app.MapControllers();
app.Run();
