import { sql } from "@/db";

interface LogErrorOpts {
  message: string;
  stack?: string | null;
  source?: "client" | "server";
  level?: "error" | "warn" | "fatal";
  url?: string | null;
  digest?: string | null;
  userId?: string | null;
  familyId?: string | null;
  userAgent?: string | null;
  metadata?: Record<string, unknown>;
}

// Persist an error event. Mirrors logAudit(): best-effort, never throws — a
// failure to record an error must never cascade into another error.
export async function logError(opts: LogErrorOpts) {
  try {
    const message = (opts.message || "Unknown error").slice(0, 2000);
    const stack = opts.stack ? opts.stack.slice(0, 8000) : null;
    await sql`
      INSERT INTO error_events (level, source, message, stack, url, digest, user_id, family_id, user_agent, metadata)
      VALUES (
        ${opts.level || "error"}, ${opts.source || "server"}, ${message}, ${stack},
        ${opts.url || null}, ${opts.digest || null}, ${opts.userId || null}, ${opts.familyId || null},
        ${opts.userAgent || null}, ${JSON.stringify(opts.metadata || {})}
      )`;
  } catch (e) {
    console.error("logError failed:", e);
  }
}
