const jwt = require("jsonwebtoken");

const verify_token = (req, res, next) => {
  const auth_header = req.headers.token;
  if (auth_header) {
    const token = auth_header.split(" ")[1];
    jwt.verify(token, "uygferuiheio", (err, user) => {
      if (err) res.status(403).json("token is not valid");
      req.user = user;
      next();
    });
  } else {
    return res.status(401).json("You are not authenticated");
  }
};

const verify_token_and_authorization = (req, res, next) => {
  verify_token(req, res, () => {
    if (req.user.id === req.params.id || req.user.is_admin) {
      next();
    } else {
      res.status(403).json("You are not allowed to do that");
    }
  });
};
const verify_token_and_admin = (req, res, next) => {
  verify_token(req, res, () => {
    if (req.user.is_admin) {
      next();
    } else {
      res.status(403).json("You are not allowed to do that");
    }
  });
};

module.exports = {
  verify_token,
  verify_token_and_authorization,
  verify_token_and_admin,
};
