// middleware/requireRole.js
const jwt = require('jsonwebtoken');

/**
 * Middleware zur Prüfung der Benutzerrolle
 * @param {string[]} allowedRoles - Erlaubte Rollen
 * @returns {function} Express-Middleware-Funktion
 */
function requireRole(allowedRoles) {
  return (req, res, next) => {
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({ error: 'Authorization header missing or invalid' });
    }

    const token = authHeader.substring(7); // "Bearer " entfernen
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      if (!decoded.role || !allowedRoles.includes(decoded.role)) {
        return res.status(403).json({ error: 'Insufficient permissions' });
      }
      req.user = decoded; // Nutzerdaten an die Request-Objekt anhängen
      next();
    } catch (err) {
      return res.status(401).json({ error: 'Invalid token' });
    }
  };
}

module.exports = requireRole;