// src/middleware/audit.js
// Central place to write to the audit_logs table. Kept as a plain helper
// (not middleware in the strict sense) so route handlers can log with full
// knowledge of what actually happened (e.g. which fields changed).
const db = require('../db');

function clientIp(req) {
  return (req.headers['x-forwarded-for'] || '').split(',')[0].trim() || req.ip || 'unknown';
}

function logAudit(req, action, entity, entityId = null, details = null, actorOverride = null) {
  try {
    db.prepare(`
      INSERT INTO audit_logs (admin_username, action, entity, entity_id, details, ip)
      VALUES (?, ?, ?, ?, ?, ?)
    `).run(
      actorOverride || (req.session && req.session.username) || 'system',
      action,
      entity,
      entityId != null ? String(entityId) : null,
      details ? String(details).slice(0, 500) : null,
      clientIp(req)
    );
  } catch (e) {
    // Auditing must never break the primary request.
    console.error('[audit] failed to write log entry:', e.message);
  }
}

module.exports = { logAudit, clientIp };
