import { db } from "@/db";
import { adminAuditEvents } from "@/db/schema";

export type AuditEvent = {
  entityType?: string;
  entityId?: string | number;
  details?: Record<string, unknown>;
};

/**
 * Records an administrative operation. Best-effort: audit failures must never
 * break the operation itself. Callers must pass no secrets, credentials or
 * image contents — identifiers and field names only.
 */
export async function recordAudit(action: string, event: AuditEvent = {}) {
  if (!db) return;
  try {
    await db.insert(adminAuditEvents).values({
      actor: process.env.ADMIN_LOGIN || "admin",
      action: action.slice(0, 100),
      entityType: event.entityType?.slice(0, 64) ?? null,
      entityId: event.entityId !== undefined && event.entityId !== null ? String(event.entityId).slice(0, 128) : null,
      details: event.details ?? null
    });
  } catch {
    // Audit is observability, not a gate; ignore storage failures.
  }
}
