import { query } from "./db";
import { safeError } from "./safe-log";

export async function auditLog(input: {
  step: string;
  channel?: string;
  outcome: string;
  ip?: string | null;
  userAgent?: string | null;
  meta?: Record<string, unknown>;
}) {
  try {
    await query(
      `INSERT INTO audit_logs (step, channel, outcome, ip, user_agent, meta)
       VALUES (:step, :channel, :outcome, :ip, :user_agent, :meta)`,
      {
        step: input.step,
        channel: input.channel || "website",
        outcome: input.outcome,
        ip: input.ip || null,
        user_agent: input.userAgent?.slice(0, 250) || null,
        meta: JSON.stringify(input.meta || {}),
      },
    );
  } catch (e) {
    safeError("audit log failed", e);
  }
}
