'use strict';
const db = require('../db/db');

const stmt = db.prepare(
  "INSERT INTO admin_audit_log (admin_id, action, target, detail, ip) VALUES (?, ?, ?, ?, ?)"
);

/**
 * Log an admin action.
 * @param {object} req - Express request (must have req.user)
 * @param {string} action - e.g. 'user.role_change', 'user.delete', 'user.ban'
 * @param {string} [target] - e.g. 'user:42', 'question:15'
 * @param {string} [detail] - human-readable detail
 */
function audit(req, action, target, detail) {
  try {
    const ip = req.ip || req.socket?.remoteAddress || '';
    stmt.run(req.user?.id || 0, action, target || null, detail || null, ip);
  } catch (e) { console.error('[audit]', e.message); }
}

module.exports = { audit };
