// lib/audit/log.ts
import { corePool } from "@/lib/db/mysql";
import { NextRequest } from "next/server";

type AuditParams = {
  actor_type: "recruiter" | "admin" | "system";
  actor_id?: number | null;

  action: string;
  entity: string;
  entity_id?: number | null;

  req?: NextRequest;
  metadata?: Record<string, any>;
};

export async function auditLog(params: AuditParams) {
  const {
    actor_type,
    actor_id = null,
    action,
    entity,
    entity_id = null,
    req,
    metadata = null,
  } = params;

  const ip =
    req?.headers.get("x-forwarded-for") ||
    req?.headers.get("x-real-ip") ||
    null;

  const userAgent = req?.headers.get("user-agent") || null;

  await corePool.query(
    `
    INSERT INTO audit_logs (
      actor_type,
      actor_id,
      action,
      entity,
      entity_id,
      ip_address,
      user_agent,
      metadata
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `,
    [
      actor_type,
      actor_id,
      action,
      entity,
      entity_id,
      ip,
      userAgent,
      metadata ? JSON.stringify(metadata) : null,
    ]
  );
}
