const { verifyJwtToken } = require("../auth/jwt");
function authorizeUser(req, res, next) {
  try {
    const token = req.cookies.token;
    if (!token) {
      return res.status(401).json({ message: "Unauthorized" });
    }

    const decoded = verifyJwtToken(token);
    if (!decoded.user_id || !decoded.username) {
      return res.status(401).json({ message: "Invalid token" });
    }

    res.setHeader("X-Content-Type-Options", "nosniff");
    res.setHeader("X-Frame-Options", "DENY");
    res.setHeader("X-XSS-Protection", "1; mode=block");

    req.user = {
      user_id: decoded.user_id,
      username: decoded.username.toString().trim(),
    };

    next();
  } catch (e) {
    console.error("Authorization failed:", e);
    return res.status(500).json({ message: "Internal server error" });
  }
}

module.exports = authorizeUser;
