using Microsoft.AspNetCore.Components.Web;
using SelectPdf;
using SelectPdf.Samples;
using SelectPdf.Samples.Components;

var builder = WebApplication.CreateBuilder(args);

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

builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<HtmlRenderer>();
builder.Services.AddScoped<IComponentHtmlRenderer, ComponentHtmlRenderer>();

var app = builder.Build();

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

ServerInfo.ServerPath = app.Environment.ContentRootPath;
ServerInfo.WebRootPath = app.Environment.WebRootPath ?? string.Empty;

// Marketing site the chrome (nav menu, logo, footer) links at. The host is
// environment-specific: the staging mirror is selectpdf.net, while dev boxes
// and production both point at the public selectpdf.com. An explicit
// "MarketingBaseUrl" config value (e.g. in an environment appsettings file)
// overrides this if a deployment ever needs a different host.
ServerInfo.MarketingBaseUrl =
    (app.Configuration["MarketingBaseUrl"]
        ?? (app.Environment.IsStaging() ? "https://selectpdf.net" : "https://selectpdf.com"))
    .TrimEnd('/');

// Apply the DenyLocalFileAccess flag from appsettings.json globally.
// When true, SelectPdf rejects any attempt to convert local files / file:// URLs.
GlobalProperties.ForceDenyLocalFileAccess =
    app.Configuration.GetValue<bool>("DenyLocalFileAccess", false);

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

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

// HTTP-inspection helper endpoints. These are reached by the SelectPdf
// converter as external HTTP requests (HttpPostRequest / HttpHeaders /
// HttpCookies samples) so they can't go through Blazor's antiforgery-
// protected SSR pipeline. They are also deliberately NOT interactive Blazor
// (@page) components: an InteractiveServer page re-renders over a websocket
// circuit AFTER the converter's request completes, wiping the request-scoped
// headers/cookies from the DOM the converter captures. Static Minimal-API
// handlers return self-contained HTML so the sent headers/cookies survive.
app.MapMethods("/ViewHttpPostData", new[] { "GET", "POST" }, ViewHelpers.ViewHttpPostData)
    .DisableAntiforgery();
app.MapGet("/ViewHttpHeaders", ViewHelpers.ViewHttpHeaders)
    .DisableAntiforgery();
app.MapGet("/ViewHttpCookies", ViewHelpers.ViewHttpCookies)
    .DisableAntiforgery();

app.Run();
