using System.Data.Common;
using Dapper;

namespace KArtSell.BuildingBlocks.Reliability;

public sealed class DapperOutboxWriter : IOutboxWriter
{
    private const string Sql = """
        insert into building_blocks.outbox_message
        (message_id, event_type, schema_version, payload_json, correlation_id, occurred_at, payload_hash)
        values (@MessageId, @EventType, @SchemaVersion, cast(@PayloadJson as jsonb), @CorrelationId, @OccurredAt, @PayloadHash)
        on conflict (message_id) do nothing;
        """;

    public Task AddAsync(DbConnection connection, DbTransaction transaction, OutboxMessage message, CancellationToken cancellationToken)
        => connection.ExecuteAsync(new CommandDefinition(Sql, message, transaction, cancellationToken: cancellationToken));
}
