import type { JsonValue } from "./errors.js"; export type AuditEventInput = { tenantId?: string | null; actorId?: string | null; actorType?: string | null; action: string; targetType?: string | null; targetId?: string | null; requestId?: string | null; metadata?: Record | null; }; export type AuditEventClient = { auditEvent: { create(args: { data: Required> & Omit; }): Promise; }; }; export async function auditEvent(input: AuditEventInput, client: AuditEventClient): Promise { return client.auditEvent.create({ data: { tenantId: input.tenantId ?? null, actorId: input.actorId ?? null, actorType: input.actorType?.trim() || "system", action: input.action, targetType: input.targetType ?? null, targetId: input.targetId ?? null, requestId: input.requestId ?? null, metadata: input.metadata ?? null, }, }); } export function withAuditMiddleware( handler: (...args: TArgs) => Promise, buildEvent: (result: TResult, args: TArgs) => AuditEventInput | null | undefined, client: AuditEventClient, ): (...args: TArgs) => Promise { return async (...args) => { const result = await handler(...args); const event = buildEvent(result, args); if (event) await auditEvent(event, client); return result; }; }