const jwt = require('jsonwebtoken');

function authRequired(secret) {
  return (req, res, next) => {
    try {
      const auth = req.headers?.authorization || '';
      const [scheme, token] = auth.split(' ');

      if (scheme !== 'Bearer' || !token) {
        return res.status(401).json({ message: 'Token faltante o malformado' });
      }

      const payload = jwt.verify(token, secret);
      req.user = payload;
      next();
    } catch (err) {
      return res.status(401).json({ message: 'Token inválido o expirado' });
    }
  };
}

module.exports = { authRequired };
