'use strict';

async function logAudit(conn, userId, action, target, targetId, details = {}) {
  const { query } = require('../config/db');
  const run = conn
    ? (sql, p) => conn.execute(sql, p)
    : (sql, p) => query(sql, p);

  try {
    await run(
      'INSERT INTO audit_log (user_id, action, target, target_id, details) VALUES (?, ?, ?, ?, ?)',
      [userId || null, action, target || null, targetId || null, JSON.stringify(details)]
    );
  } catch (err) {
    console.error('[AUDIT] Log failed:', err.message);
  }
}

module.exports = { logAudit };
