const jwt = require("jsonwebtoken");

module.exports = (req, res, next) => {
  const authHeader = req.headers.authorization;

  // token yoksa normal devam
  if (!authHeader) {
    req.user = null;
    return next();
  }

  const parts = authHeader.split(" ");
  const token = parts.length === 2 ? parts[1] : null;

  if (!token) {
    req.user = null;
    return next();
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = {
      ...decoded,
      userId: Number(decoded.userId),
    };
    return next();
  } catch (err) {
    // token varsa ama bozuksa => 401 (tercih)
    return res.status(401).json({ error: "Token geçersiz" });
  }
};
