const { verifyToken } = require("../services/authService");

function requireAuth(req, res, next) {
  const authHeader = req.headers.authorization || "";
  const match = authHeader.match(/^Bearer\s+(.+)$/i);

  if (!match) {
    return res.status(401).json({ error: "missing bearer token" });
  }

  try {
    req.user = verifyToken(match[1]);
    return next();
  } catch {
    return res.status(401).json({ error: "invalid token" });
  }
}

module.exports = {
  requireAuth
};
