import type { PrismaClient } from "@capakraken/db";
import { createAuditEntry } from "./audit.js";

type AuditAction = "CREATE" | "UPDATE" | "DELETE" | "SHIFT" | "IMPORT";
type AuditSource = "ui" | "api" | "ai" | "import" | "cron";

interface BoundAuditParams {
  entityType: string;
  entityId: string;
  entityName?: string;
  action: AuditAction;
  before?: Record<string, unknown>;
  after?: Record<string, unknown>;
  summary?: string;
  metadata?: Record<string, unknown>;
}

/**
 * Creates a fire-and-forget audit logger with db, userId, and source pre-bound.
 * Use at the top of a procedure after resolving the current user.
 *
 * @example
 * const audit = makeAuditLogger(ctx.db, userRecord?.id);
 * audit({ entityType: "Vacation", entityId: v.id, action: "UPDATE", after: v });
 */
export function makeAuditLogger(
  db: PrismaClient,
  userId: string | undefined,
  source: AuditSource = "ui",
): (params: BoundAuditParams) => void {
  return (params) => {
    void createAuditEntry({ db, ...(userId !== undefined ? { userId } : {}), source, ...params });
  };
}
