using FastBlog.Core;
using FastBlog.Web;
using FastBlog.Web.Middlewares;
using Microsoft.AspNetCore.RateLimiting;
using RainCrab.Plugins.AspNet;
using RainCrab.Plugins.AspNet.Extensions;
var builder = WebApplication.CreateBuilder(args);

if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == Environments.Development)
    builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
else 
    builder.Services.AddControllersWithViews();

builder.Services.AddCore(builder.Configuration);
builder.Services.Configure<DisplayOptions>(builder.Configuration.GetSection("Display"));

builder.Services.AddRateLimiter(rateLimiterOptions =>
{
    rateLimiterOptions.AddFixedWindowLimiter(policyName: "fixed", options =>
        {
            options.PermitLimit = 30;
            options.Window = TimeSpan.FromSeconds(300);
            options.QueueLimit = 0;
        })
        .OnRejected += (context, _) =>
    {
        context.HttpContext.Response.StatusCode = 200;

        if (context.HttpContext.Request.Headers.ContainsKey("HX-Request"))
        {
            context.HttpContext.Response.Headers.Append("HX-Redirect", "/too-many-requests");
        }
        else
        {
            context.HttpContext.Response.Redirect("/too-many-requests");
        }
        return ValueTask.CompletedTask;
    };
});

WebPluginLoadContext webPluginLoadContext;

await using (var tempServiceProvider = builder.Logging.Services.BuildServiceProvider())
{
    var logger = tempServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger("PreBuildLogger");
    webPluginLoadContext = await builder.AddWebPlugins(logger, AppContext.BaseDirectory);
}

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}

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

app.UseRouting();

app.UseRateLimiter();

app.UseAuthorization();

app.UseMiddleware<SimpleAuthMiddleware>();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Blogs}/{action=Index}/{slug?}");

await app.Services.MigrateUp(app.Configuration);

await app.RunAsync();

foreach (IWebPlugin plugin in webPluginLoadContext.LoadedPlugins)
{
    await plugin.ShutdownAsync(webPluginLoadContext);
}


return;