const jwt = require("jsonwebtoken");

module.exports = (req, res, next) => {
  // 1) Check for Authorization: Bearer <token>
  const authHeader = req.headers["authorization"];
  if (authHeader && authHeader.startsWith("Bearer ")) {
    const token = authHeader.split(" ")[1];
    return jwt.verify(
      token,
      process.env.JWT_SECRET || "your_jwt_secret",
      (err, decoded) => {
        if (err) {
          return res
            .status(403)
            .json({ message: "Invalid or expired token" });
        }

        req.user = { userId: decoded.userId };
        return next();
      }
    );
  }

  // 2) Fallback: check x-user-id if no Bearer token
  const userId = req.headers["x-user-id"];
  if (userId) {
    req.user = { userId: userId };
    return next();
  }

  // 3) Neither a valid Bearer token nor x-user-id was provided
  return res
    .status(401)
    .json({ message: "Unauthorized: no token or user ID provided." });
};