const { verifyJwtToken } = require("../auth/jwt");
const { isValidUsername } = require("./filter");

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.message) {
      return res.status(401).json({ message: decoded.message });
    }

    if (!isValidUsername(decoded.username)) {
      console.error("Invalid username on decoding JWT (that's weird)");
      return res.status(401).json({
        message: "Authorization failed, try to delete cookies and try again",
      });
    }

    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;
