using Dapper;
using Npgsql;
namespace KBX.Shared.Authorization;

public sealed class SensitiveDataDisclosureAuditWriter(NpgsqlDataSource dataSource)
{
    public async Task WriteAsync(KbxSensitiveDisclosure disclosure, CancellationToken ct)
    {
        const string sql = """
        insert into kbx.sensitive_data_disclosures
        (tenant_id,user_id,policy_id,entity_type,entity_id,fields,reason,correlation_id,occurred_at)
        values (@TenantId,@UserId,@PolicyId,@EntityType,@EntityId,@Fields::jsonb,@Reason,@CorrelationId,now())
        """;
        await using var connection = await dataSource.OpenConnectionAsync(ct);
        await connection.ExecuteAsync(new CommandDefinition(sql, new {
            disclosure.TenantId, disclosure.UserId, disclosure.PolicyId, disclosure.EntityType,
            disclosure.EntityId, Fields = System.Text.Json.JsonSerializer.Serialize(disclosure.Fields),
            disclosure.Reason, disclosure.CorrelationId }, cancellationToken: ct));
    }
}
