// middleware/auditLogger.js
const db = require('../db');

/**
 * Middleware zur Protokollierung sensibler Aktionen
 * @param {string} action - Name der Aktion (z.B. 'USER_SUSPEND')
 * @param {string} targetType - Typ des Zielobjekts (z.B. 'user')
 * @returns {function} Express-Middleware-Funktion
 */
function auditLogger(action, targetType) {
  return async (req, res, next) => {
    try {
      const timestamp = new Date().toISOString();
      const actorUserId = req.user?.id || null;
      const targetId = req.params.id || req.body.id || null;
      const reason = req.body.reason || null;

      // Audit-Eintrag in die Datenbank schreiben
      await db.run(
        'INSERT INTO audit_log (timestamp, actor_user_id, action, target_type, target_id, reason) VALUES (?, ?, ?, ?, ?, ?)',
        [timestamp, actorUserId, action, targetType, targetId, reason]
      );

      next();
    } catch (err) {
      console.error('Audit logging failed:', err);
      // Fehler bei Audit-Logging sollte nicht den Request blockieren
      next();
    }
  };
}

module.exports = auditLogger;