using Scalar.AspNetCore;
using Serilog;
using Tiku.Api.Logging;
using Tiku.Api.Middleware;
using Tiku.Api.Options;
using Tiku.Api.Security;

namespace Tiku.Api.Configuration;

public static class ApplicationBuilderExtensions
{
    public static WebApplication UseApiPipeline(this WebApplication app)
    {
        if (app.Environment.IsDevelopment())
        {
            app.MapOpenApi().AllowAnonymous();
            app.MapScalarApiReference(options => options
                    .WithTitle("TIKU Backend API")
                    .AddPreferredSecuritySchemes("BearerAuth")
                    .EnablePersistentAuthentication())
                .AllowAnonymous();
        }

        app.UseSerilogRequestLogging(SerilogRequestLogging.ConfigureRequestLogging);
        app.UseMiddleware<DatabaseRequestMetricsMiddleware>();
        app.UseMiddleware<ExceptionHandlingMiddleware>();
        app.UseForwardedHeaders();
        app.UseHttpsRedirection();
        app.UseResponseCompression();
        app.UseRouting();
        app.UseCors(CorsOptions.PolicyName);
        app.UseMiddleware<TenantResolutionMiddleware>();
        app.UseMiddleware<BrowserCsrfMiddleware>();
        app.UseAuthentication();
        app.UseMiddleware<AuthRateLimitPartitionMiddleware>();
        app.UseRateLimiter();
        app.UseMiddleware<CurrentPrincipalMiddleware>();
        app.UseAuthorization();
        app.UseMiddleware<SaasFeatureAccessMiddleware>();
        app.UseOutputCache();
        app.MapControllers();

        return app;
    }
}
