import { auditLog } from "./schema"; import { uuidv7 } from "@/lib/uuid"; /** * Audit-log helpers — unit D8 (BUILD-SPEC §7 rule 12: every admin mutation * writes an audit row). * * `auditRow()` is pure: it builds the row object (uuidv7 id, JSON payloads, * an injectable `now`) so it can be unit-tested without a database. * `writeAudit()` takes the Drizzle client as a parameter (dependency * injected) and inserts the row; the app never updates or deletes a row. */ export interface AuditRow { id: string; actorId: string; actorIpHash: string | null; action: string; entityType: string; entityId: string | null; beforeJson: string; afterJson: string; createdAt: Date; } export interface AuditInput { actorId: string; action: string; entityType: string; entityId?: string | null; actorIpHash?: string | null; before?: Record; after?: Record; /** Injectable UTC instant (defaults to now) so tests are deterministic. */ now?: Date; } /** Build an append-only audit row. Pure — no database. */ export function auditRow(input: AuditInput): AuditRow { return { id: uuidv7(), actorId: input.actorId, actorIpHash: input.actorIpHash ?? null, action: input.action, entityType: input.entityType, entityId: input.entityId ?? null, beforeJson: input.before ? JSON.stringify(input.before) : "", afterJson: input.after ? JSON.stringify(input.after) : "", createdAt: input.now ?? new Date(), }; } /** Insert an audit row via the injected Drizzle client. */ export async function writeAudit( db: typeof import("@/db").db, input: AuditInput, ): Promise { const row = auditRow(input); await db.insert(auditLog).values({ id: row.id, actorId: row.actorId, actorIpHash: row.actorIpHash, action: row.action, entityType: row.entityType, entityId: row.entityId, beforeJson: row.beforeJson, afterJson: row.afterJson, createdAt: row.createdAt, }); return row; }