const jwt = require("jsonwebtoken");

const authenticateToken = (req, res, next) => {
  const token = req.header("Authorization")?.split(" ")[1]; // Get token from Authorization header

  if (!token) {
    return res.status(403).json({ message: "Access denied" });
  }

  try {
    // Verify token
    const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY);
    req.user = decoded; // Store decoded token (user data) in request object
    next(); // Pass to the next middleware or route handler
  } catch (error) {
    if (error.name === "TokenExpiredError") {
      return res.status(401).json({
        message: "Token expired. Please refresh your token.",
        refreshTokenRequired: true, // Indicate that a refresh token is needed
      });
    }  
    res.status(401).json({ message: "Invalid or expired token" });
  }
};

module.exports = { authenticateToken };
