using LiteCharms.Features.Extensions;
using LiteCharms.Features.Postgres;
using MidrandBookshop;
using MidrandBookshop.Components;
using static LiteCharms.Features.Extensions.Quartz;

var builder = WebApplication.CreateBuilder(args);

builder.AddMonitoring();
builder.Services.RegisterServices(builder.Configuration);

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    app.UseHsts();
}

app.UseForwardedHeaders();
app.UseHttpsRedirection();

app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.UseHealthChecks("/health", new HealthCheckOptions
{
    ResponseWriter = HealthChecks.UI.Client.UIResponseWriter.WriteHealthCheckUIResponse
});

app.MapStaticAssets();
app.UseCookiePolicy();

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

using (var security = app.Services.CreateScope())
{
    var dataProtectionContext = security.ServiceProvider.GetRequiredService<DataProtectionDbContext>();

    await dataProtectionContext.Database.MigrateAsync();
}

var schedulerFactory = app.Services.GetRequiredService<ISchedulerFactory>();
var scheduler = await schedulerFactory.GetScheduler(MidrandShopSchedulerName);

if (!scheduler!.IsStarted) await scheduler.Start();

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

app.Run();