import { randomUUID } from 'node:crypto';
import type { Queryable } from '../db/types.js';

export interface AuditContext {
  actorId?: string | null;
  actorRole?: string | null;
  ip?: string | null;
  userAgent?: string | null;
}

export interface AuditInput {
  action: string;
  entityType: string;
  entityId: string;
  oldValues?: unknown;
  newValues?: unknown;
  reason?: string | null;
  importId?: string | null;
  deliveryEventId?: string | null;
}

export async function appendAudit(tx: Queryable, context: AuditContext, input: AuditInput): Promise<string> {
  const id = randomUUID();
  await tx.query(
    `INSERT INTO audit_events
      (id, actor_id, actor_role, action, entity_type, entity_id, old_values, new_values, reason,
       ip_address, user_agent, import_id, delivery_event_id)
     VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8::jsonb,$9,$10::inet,$11,$12,$13)`,
    [
      id,
      context.actorId ?? null,
      context.actorRole ?? null,
      input.action,
      input.entityType,
      input.entityId,
      input.oldValues === undefined ? null : JSON.stringify(input.oldValues),
      input.newValues === undefined ? null : JSON.stringify(input.newValues),
      input.reason ?? null,
      context.ip ?? null,
      context.userAgent ?? null,
      input.importId ?? null,
      input.deliveryEventId ?? null
    ]
  );
  return id;
}

