const jwt = require('jsonwebtoken');
const SECRET = () => process.env.JWT_SECRET || 'dev_secret';

function authRequired(req, res, next) {
  const auth = req.headers.authorization || '';
  const token = auth.startsWith('Bearer ') ? auth.slice(7) : null;
  if (!token) return res.status(401).json({ error: 'Token requerido' });
  try {
    req.user = jwt.verify(token, SECRET());
    next();
  } catch {
    return res.status(401).json({ error: 'Token inválido o expirado' });
  }
}

function requireRole(...roles) {
  return (req, res, next) => {
    if (!req.user) return res.status(401).json({ error: 'No autenticado' });
    if (!roles.includes(req.user.role)) return res.status(403).json({ error: 'Sin permisos' });
    next();
  };
}

function signToken(payload) {
  return jwt.sign(payload, SECRET(), { expiresIn: process.env.JWT_EXPIRES_IN || '8h' });
}

module.exports = { authRequired, requireRole, signToken };
