using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.AspNetCore.HttpOverrides;
using RpgRoller.Api;
using RpgRoller.Components;
using RpgRoller.Contracts;
using RpgRoller.Hosting;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRpgRollerCore(builder.Configuration, builder.Environment);
builder.Services.AddRazorComponents().AddInteractiveServerComponents();
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    options.KnownIPNetworks.Clear();
    options.KnownProxies.Clear();
});
builder.Services.AddResponseCompression(options =>
{
    options.EnableForHttps = true;
    options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(["application/json"]);
});
builder.Services.ConfigureHttpJsonOptions(options => RpgRollerJson.Configure(options.SerializerOptions));
builder.Services.AddScoped<RpgRollerApiClient>();
builder.Services.AddScoped<WorkspaceQueryService>();

var app = builder.Build();
app.InitializeRpgRollerState();
app.UseForwardedHeaders();

var configuredPathBase = builder.Configuration["PathBase"];
if (!string.IsNullOrWhiteSpace(configuredPathBase))
{
    var normalizedPathBase = configuredPathBase.Trim();
    if (!normalizedPathBase.StartsWith('/'))
        normalizedPathBase = $"/{normalizedPathBase}";

    normalizedPathBase = normalizedPathBase.TrimEnd('/');
    if (normalizedPathBase.Length > 0)
        app.UsePathBase(normalizedPathBase);
}

app.UseResponseCompression();
app.UseAntiforgery();

app.MapRpgRollerApi();
app.MapFrontendEntryEndpoints();
app.MapStaticAssets();
app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
app.Run();

public partial class Program;