using Dapper;
using FastEndpoints;
using KArtSell.BuildingBlocks.Data;

namespace KArtSell.Modules.ModelOperations.Features.GetApprovalQueue;

public sealed class Endpoint(IDbConnectionFactory connectionFactory) : EndpointWithoutRequest<Response>
{
    public override void Configure()
    {
        Get("/api/v1/approval-queue");
        Roles("Risk", "Compliance", "Trading");
        Tags("ModelOperations");
    }

    public override async Task HandleAsync(CancellationToken ct)
    {
        await using var connection = await connectionFactory.OpenAsync(ct);

        var queue = await connection.QueryAsync<ApprovalItem>("""
            SELECT
                id,
                run_id AS RunId,
                model_id AS ModelId,
                status AS Status,
                approved_by AS ApprovedBy,
                approval_reason AS ApprovalReason,
                rejection_reason AS RejectionReason,
                requested_at AS RequestedAt,
                approved_at AS ApprovedAt,
                rejected_at AS RejectedAt
            FROM model_operations.approval_queue
            ORDER BY
                CASE WHEN status = 'Pending' THEN 0 ELSE 1 END,
                requested_at DESC
            """);

        await Send.OkAsync(new Response(queue.ToArray()), ct);
    }
}
