const jwt = require('jsonwebtoken');
const { isTokenBlacklisted } = require('../utils/blacklist');

const authMiddleware = (req, res, next) => {
  const authHeader = req.header('Authorization');
  if (!authHeader) {
    return res.status(401).json({ message: 'Zugriff verweigert. Kein Token vorhanden.' });
  }
  const token = authHeader.replace('Bearer ', '');
  if (isTokenBlacklisted(token)) {
    return res.status(401).json({ message: 'Token wurde gesperrt.' });
  }
  try {
    const decoded = jwt.verify(token, 'zTxVgptmPl9!_dr%xxx9999(dd)');
    req.user = decoded;
    next();
  } catch (err) {
    return res.status(401).json({ message: 'Ungültiges Token.' });
  }
};

module.exports = authMiddleware;
