using Dapper;
using Npgsql;

namespace Books.Api.EventFlow.Repositories;

/// <summary>
/// Repository for querying ledger transaction data by idempotency key.
/// Used for idempotent retry handling when ledger returns "already processed".
/// </summary>
public class LedgerTransactionRepository(NpgsqlDataSource dataSource) : ILedgerTransactionRepository
{
    public async Task<string?> GetTransactionIdByIdempotencyKeyAsync(
        string idempotencyKey,
        CancellationToken ct = default)
    {
        await using var connection = await dataSource.OpenConnectionAsync(ct);

        // Query ledger_entries table for the idempotency key
        // The id column contains the transaction ID (UUID)
        var sql = """
            SELECT id::text
            FROM ledger_entries
            WHERE idempotency_key = @Key
            LIMIT 1
            """;

        return await connection.QueryFirstOrDefaultAsync<string>(sql, new { Key = idempotencyKey });
    }
}
