import type { Pool, PoolConnection } from "mysql2/promise";
import { pool as defaultPool } from "../db/mysql.js";

/**
 * Registro de auditoria (`audit_log`). Toda escrita que mexe em config
 * sensível ou dispara efeito externo deve passar por aqui (CLAUDE.md).
 *
 * `detail` é gravado como JSON — NUNCA inclua segredos em claro (api_secret,
 * senha de proxy, CPF/PIX). Para identificar um segredo, use os últimos 4
 * dígitos (`lastFour`).
 */

export interface AuditEntry {
  /** Quem fez a ação (panel_users.id). Null para ações de sistema/scripts. */
  userId?: number | null;
  /** Verbo curto, ex: "account.create", "account.update", "auth.login". */
  action: string;
  /** Tipo da entidade afetada, ex: "exchange_account". */
  entity?: string | null;
  /** Id da entidade afetada (string para caber qualquer tipo). */
  entityId?: string | number | null;
  /** Contexto adicional, sem segredos. */
  detail?: Record<string, unknown> | null;
}

export async function writeAudit(
  entry: AuditEntry,
  conn: Pool | PoolConnection = defaultPool,
): Promise<void> {
  await conn.query(
    `INSERT INTO audit_log (user_id, action, entity, entity_id, detail)
     VALUES (:userId, :action, :entity, :entityId, :detail)`,
    {
      userId: entry.userId ?? null,
      action: entry.action,
      entity: entry.entity ?? null,
      entityId: entry.entityId != null ? String(entry.entityId) : null,
      detail: entry.detail ? JSON.stringify(entry.detail) : null,
    },
  );
}
