import type { Db } from '../db/client.ts' import { auditLog } from '../db/schema.ts' interface AuditEntry { organizationId: string actorId: string | null entityType: string entityId: string action: string changes?: Record | null } export async function audit(db: Db, entry: AuditEntry): Promise { await db.insert(auditLog).values({ ...entry, changes: entry.changes ?? null }) } const comparable = (value: unknown) => (value instanceof Date ? value.toISOString() : (value ?? null)) /** `{ field: [before, after] }` for each field in `next` whose value differs from `current`. */ export function diff(current: Record, next: Record): Record { const changes: Record = {} for (const [key, value] of Object.entries(next)) { if (value === undefined) continue const before = comparable(current[key]) const after = comparable(value) if (JSON.stringify(before) !== JSON.stringify(after)) changes[key] = [before, after] } return changes }