using LiteCharms.Features.Extensions;
using LiteCharms.Features.Mediator;
using LiteCharms.Features.MidrandBooks.Extensions;
using Microsoft.AspNetCore.HttpOverrides;
using MidrandBookshop.Components;
using static LiteCharms.Features.Extensions.Quartz;

AppContext.SetSwitch("Microsoft.IdentityModel.DisableTelemetry", true);

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

builder.AddMonitoring();
builder.Services.AddEndpointsApiExplorer();

builder.Services.AddMediator();
builder.Services.AddAuthentikUiSecurity(builder.Configuration);

builder.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(TelemetryPipelineBehavior<,>));
builder.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(LoggingPipelineBehavior<,>));

builder.Services.AddQuartzSchedulerClient(MidrandShopSchedulerName, builder.Configuration);

builder.Services.AddEmailServices(builder.Configuration);
builder.Services.AddEmailServiceBus();

builder.Services.AddHttpClient();
builder.Services.AddShopServices();
builder.Services.AddHashServices(builder.Configuration);
builder.Services.AddMidrandShopDatabase(builder.Configuration);

builder.Services.AddMidrandShopPostgresHealthCheck();
builder.Services.AddMidrandShopQuartzHealthCheck();
builder.Services.AddHealthChecksSupport(builder.Configuration);
builder.Services.AddCascadingAuthenticationState();

builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    options.KnownProxies.Clear();
});

var app = builder.Build();

app.UseForwardedHeaders();
app.AddSecurityEndpoints();

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

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

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

app.UseHealthChecks("/health", new HealthCheckOptions
{
    ResponseWriter = HealthChecks.UI.Client.UIResponseWriter.WriteHealthCheckUIResponse
});

app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.UseHttpsRedirection();

app.UseAntiforgery();

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

app.Run();