using Predictalytics.Api.Endpoints;
using Predictalytics.Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using System;

namespace Predictalytics.Api;

/// <summary>
/// Configures the API WebApplication. Used by the embedded Kestrel server.
/// </summary>
public static class ApiConfiguration
{
    public static WebApplication ConfigureApi(WebApplicationBuilder builder, string? connectionStringOverride = null)
    {
        builder.Services.AddPredictalytics(builder.Configuration, connectionStringOverride);
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen(c => c.SwaggerDoc("v1",
            new() { Title = "Predictalytics Analytics API", Version = "v1" }));
        var allowedOrigins = builder.Configuration.GetSection("ApiSettings:AllowedOrigins").Get<string[]>() 
            ?? new[] { "http://localhost:5000" };
        builder.Services.AddCors(o => o.AddDefaultPolicy(p =>
            p.WithOrigins(allowedOrigins).AllowAnyMethod().AllowAnyHeader()));

        var app = builder.Build();

        app.UseCors();
        app.UseSwagger();
        app.UseSwaggerUI();
        app.UseDefaultFiles();
        app.UseStaticFiles(new StaticFileOptions
        {
            // Internal dashboard: always revalidate so UI fixes reach the browser immediately.
            OnPrepareResponse = ctx => ctx.Context.Response.Headers.CacheControl = "no-cache"
        });

        // Register both Read and Control endpoints for the local host
        app.MapPredictalyticsReadEndpoints();
        app.MapPredictalyticsControlEndpoints();

        return app;
    }

    /// <summary>
    /// Registers all Read-only endpoints designed for viewing and analysis.
    /// Safely exposed publicly since these endpoints perform no DB writes.
    /// </summary>
    public static void MapPredictalyticsReadEndpoints(this IEndpointRouteBuilder routes)
    {
        routes.MapDashboardEndpoints();
        routes.MapTraderReadEndpoints();
        routes.MapAlertReadEndpoints();
        routes.MapMarketEndpoints();
        routes.MapSearchEndpoints();
        routes.MapWatchlistEndpoints();
        routes.MapGet("/api/health", () => Results.Ok(new { Status = "OK", Timestamp = DateTime.UtcNow }));

        routes.MapGet("/api/capabilities", (IConfiguration config) =>
        {
            var canControl = config.GetValue<bool>("ApiSettings:CanControl", true);
            var authRequired = config.GetValue<bool>("ApiSettings:AuthRequired", false);
            return Results.Ok(new { CanControl = canControl, AuthRequired = authRequired });
        });
    }

    /// <summary>
    /// Registers all Control endpoints that trigger crawls, modifications, or database updates.
    /// Excluded from the Public API routing to ensure system security.
    /// </summary>
    public static void MapPredictalyticsControlEndpoints(this IEndpointRouteBuilder routes)
    {
        routes.MapTraderControlEndpoints();
        routes.MapAlertControlEndpoints();
        routes.MapJobEndpoints();
        routes.MapDevEndpoints();
    }
}
