const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);

const requireCsrf = (req, res, next) => {
    if (SAFE_METHODS.has(req.method.toUpperCase())) {
        return next();
    }

    if (!req.session || !req.session.user) {
        return res.status(403).json({
            error: 'Zugriff verweigert',
            reason: 'SESSION_REQUIRED'
        });
    }

    if (!req.session.csrfToken) {
        return res.status(403).json({
            error: 'CSRF erforderlich',
            reason: 'CSRF_SESSION_MISSING'
        });
    }

    const headerToken = req.headers['x-csrf-token'];
    if (!headerToken) {
        return res.status(403).json({
            error: 'CSRF erforderlich',
            reason: 'CSRF_HEADER_MISSING'
        });
    }

    if (headerToken !== req.session.csrfToken) {
        return res.status(403).json({
            error: 'CSRF ungültig',
            reason: 'CSRF_TOKEN_INVALID'
        });
    }

    next();
};

module.exports = { requireCsrf };
