using Dapper;
using Npgsql;

namespace Books.Api.EventFlow.Repositories;

/// <summary>
/// PostgreSQL implementation of the document hash repository.
/// </summary>
public class DocumentHashRepository(NpgsqlDataSource dataSource) : IDocumentHashRepository
{
    public async Task<DocumentHashRecord?> GetByHashAsync(
        string companyId,
        string contentHash,
        CancellationToken cancellationToken = default)
    {
        await using var connection = await dataSource.OpenConnectionAsync(cancellationToken);

        const string sql = """
            SELECT
                id::text AS Id,
                company_id AS CompanyId,
                content_hash AS ContentHash,
                original_filename AS OriginalFilename,
                attachment_id::text AS AttachmentId,
                draft_id::text AS DraftId,
                created_at AS CreatedAt
            FROM document_content_hashes
            WHERE company_id = @CompanyId AND content_hash = @ContentHash
            """;

        return await connection.QuerySingleOrDefaultAsync<DocumentHashRecord>(
            sql,
            new { CompanyId = companyId, ContentHash = contentHash });
    }

    public async Task InsertAsync(
        string companyId,
        string contentHash,
        string originalFilename,
        string? attachmentId,
        string? draftId,
        CancellationToken cancellationToken = default)
    {
        await using var connection = await dataSource.OpenConnectionAsync(cancellationToken);

        const string sql = """
            INSERT INTO document_content_hashes (company_id, content_hash, original_filename, attachment_id, draft_id)
            VALUES (@CompanyId, @ContentHash, @OriginalFilename, @AttachmentId, @DraftId)
            ON CONFLICT (company_id, content_hash) DO NOTHING
            """;

        await connection.ExecuteAsync(
            sql,
            new
            {
                CompanyId = companyId,
                ContentHash = contentHash,
                OriginalFilename = originalFilename,
                AttachmentId = attachmentId,
                DraftId = draftId
            });
    }
}
