const jwt = require('jsonwebtoken');

const verifyToken = (req, res, next) => {
  let token = req.headers['authorization'];

  // Check cookies if no auth header
  if (!token && req.cookies && req.cookies.token) {
    token = req.cookies.token;
  } else if (token && token.startsWith('Bearer ')) {
    token = token.slice(7, token.length).trimLeft();
  }

  if (!token) return res.status(403).json({ error: 'Token missing from header' });

  jwt.verify(token, process.env.JWT_SECRET || 'supersecret123', (err, decoded) => {
    if (err) return res.status(401).json({ error: 'Unauthorized' });
    req.user = decoded;
    next();
  });
};

module.exports = { verifyToken };
