using System.Data.Common;
using Dapper;

namespace KArtSell.BuildingBlocks.Reliability;

public sealed class DapperInboxStore : IInboxStore
{
    private const string Sql = """
        insert into building_blocks.inbox_message
        (consumer, message_id, received_at, payload_hash)
        values (@Consumer, @MessageId, @ReceivedAt, @PayloadHash)
        on conflict (consumer, message_id) do nothing;
        """;

    public async Task<bool> TryBeginAsync(
        DbConnection connection,
        DbTransaction transaction,
        string consumer,
        Guid messageId,
        string payloadHash,
        DateTimeOffset receivedAt,
        CancellationToken cancellationToken)
    {
        var affected = await connection.ExecuteAsync(new CommandDefinition(
            Sql,
            new { Consumer = consumer, MessageId = messageId, ReceivedAt = receivedAt, PayloadHash = payloadHash },
            transaction,
            cancellationToken: cancellationToken));
        return affected == 1;
    }
}
