const jwt = require('jsonwebtoken');
const config = require('../config/env');

const authenticateHandler = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ success: false, message: 'Kein Token bereitgestellt' });
  }

  try {
    const decoded = jwt.verify(token, config.jwtSecret);
    if (decoded.role !== 'handler') {
      return res.status(403).json({ success: false, message: 'Zugriff verweigert' });
    }
    req.handlerUser = decoded;
    next();
  } catch (error) {
    return res.status(403).json({ success: false, message: 'Ungültiger oder abgelaufener Token' });
  }
};

module.exports = { authenticateHandler };
