const jwt = require("jsonwebtoken");
const config = require("config");
const { CompanyUsers } = require("../models/CompanyUsers");

module.exports = async function (req, res, next) {
  const token = req.header("x-auth-token");
  console.log("TOKEN", token);
  try {
    if (!token) {
      console.log("NO TOKEN");
      return res.status(401).send("Access denied. No token provided.");
    }
    const decoded = jwt.verify(token, config.get("jwtPrivateKey"));
    let user = await CompanyUsers.findById(decoded._id);
    if (!user) {
      console.log("Invalid token: User Dont exist");
      return res.status(400).send("Invalid token: User Dont exist");
    }
    req.user = user;
    return next();
  } catch (err) {
    console.log("ERR: ", err);
    return res.status(400).send("Error in validating token");
  }
};
