using FastEndpoints;
using QuantEngine.Infrastructure.Data;
using Dapper;

namespace QuantEngine.Web.Endpoints;

public class DatabaseTablesResponse
{
    public List<string> Tables { get; set; } = new();
}

public class DatabaseRowsRequest
{
    public string TableName { get; set; } = string.Empty;
}

public class DatabaseRowsResponse
{
    public string TableName { get; set; } = string.Empty;
    public List<string> Columns { get; set; } = new();
    public List<Dictionary<string, object?>> Rows { get; set; } = new();
}

[HttpGet("/api/database/tables")]
public class GetDatabaseTablesEndpoint : EndpointWithoutRequest<DatabaseTablesResponse>
{
    private readonly IDbConnectionFactory _connectionFactory;

    public GetDatabaseTablesEndpoint(IDbConnectionFactory connectionFactory)
    {
        _connectionFactory = connectionFactory;
    }

    public override async Task HandleAsync(CancellationToken ct)
    {
        var whitelistedTables = new List<string>
        {
            "public.market_raw_history",
            "public.factor_version_history",
            "public.factor_output_history",
            "public.decision_result_history",
            "public.order_waterfall_execution_history",
            "public.shadow_ledger_history",
            "public.scheduler_state_history"
        };

        try
        {
            using var conn = _connectionFactory.CreateConnection();
            var sql = "SELECT table_schema || '.' || table_name FROM information_schema.tables WHERE table_schema IN ('public') ORDER BY table_name;";
            var tables = (await conn.QueryAsync<string>(sql)).ToList();
            await SendAsync(new DatabaseTablesResponse { Tables = tables.Count > 0 ? tables : whitelistedTables }, 200, ct);
        }
        catch
        {
            await SendAsync(new DatabaseTablesResponse { Tables = whitelistedTables }, 200, ct);
        }
    }
}
