using Backend.Data;
using Microsoft.EntityFrameworkCore;

namespace Backend.Endpoints;

public static class SystemEndpoints
{
    public static IEndpointRouteBuilder MapSystemEndpoints(this IEndpointRouteBuilder app)
    {
        app.MapGet("/api/health", () => Results.Ok(new { status = "ok" }))
            .WithName("GetHealth")
            .WithOpenApi();

        app.MapGet("/api/health/database", async (AwardsDbContext db, IConfiguration configuration) =>
        {
            var source = configuration["VTSA_POSTGRES"] is not null ? "environment" : "appsettings";

            try
            {
                var canConnect = await db.Database.CanConnectAsync();
                var pendingMigrations = canConnect
                    ? await db.Database.GetPendingMigrationsAsync()
                    : Array.Empty<string>();

                return Results.Ok(new
                {
                    provider = "postgres",
                    canConnect,
                    pendingMigrations,
                    configuredConnection = new { source },
                });
            }
            catch (Exception exception)
            {
                return Results.Ok(new
                {
                    provider = "postgres",
                    canConnect = false,
                    pendingMigrations = Array.Empty<string>(),
                    configuredConnection = new { source },
                    error = exception.Message,
                });
            }
        })
        .WithName("GetDatabaseHealth")
        .WithOpenApi();

        return app;
    }
}
