import { sql } from "@/db";

interface AuditOpts {
  familyId?: string;
  userId?: string;
  action: string;
  resourceType?: string;
  resourceId?: string;
  request?: Request;
  metadata?: Record<string, unknown>;
}

export async function logAudit(opts: AuditOpts) {
  try {
    const ip = opts.request?.headers.get("x-forwarded-for")?.split(",")[0]
      || opts.request?.headers.get("x-real-ip");
    const ua = opts.request?.headers.get("user-agent");

    await sql`
      INSERT INTO audit_log (family_id, user_id, action, resource_type, resource_id, ip_address, user_agent, metadata)
      VALUES (${opts.familyId || null}, ${opts.userId || null}, ${opts.action},
              ${opts.resourceType || null}, ${opts.resourceId || null},
              ${ip || null}, ${ua || null}, ${JSON.stringify(opts.metadata || {})})`;
  } catch (e) {
    console.error("Audit log failed:", e);
    // Never throw - audit failures shouldn't break the request
  }
}