/**
 * Audit-Log Middleware für Management Routes
 * Loggt alle Aktionen im Management Portal für Security & Compliance
 */

const auditLogRepository = require('../repositories/ManagementAuditLogRepository');

/**
 * Middleware zum Loggen von Management-Aktionen
 * Fügt res.auditLog() Funktion hinzu
 */
const auditLogMiddleware = (req, res, next) => {
    // Extrahiere Client-Informationen
    const ipAddress = req.ip || req.connection.remoteAddress || 'unknown';
    const userAgent = req.get('user-agent') || 'unknown';
    const managementToken = req.params.token || null;
    const sourceHost = req.get('x-forwarded-host') || req.get('host') || 'unknown';
    const sourceType = req.requestSource || 'unknown';

    /**
     * Log-Funktion für Controllers
     * @param {string} action - Aktion (z.B. 'validate_token', 'revoke_consent')
     * @param {boolean} success - Erfolg
     * @param {string} groupId - Gruppen-ID (optional)
     * @param {string} errorMessage - Fehlermeldung (optional)
     * @param {Object} requestData - Request-Daten (optional)
     */
    res.auditLog = async (action, success, groupId = null, errorMessage = null, requestData = null) => {
        try {
            await auditLogRepository.logAction({
                groupId,
                managementToken,
                action,
                success,
                errorMessage,
                ipAddress,
                userAgent,
                requestData,
                sourceHost,
                sourceType
            });
        } catch (error) {
            console.error('Failed to write audit log:', error);
            // Audit-Log-Fehler sollen die Hauptoperation nicht blockieren
        }
    };

    next();
};

module.exports = auditLogMiddleware;
