import jwt from "jsonwebtoken";
import SalesCoOrdinator from "../resources/SalesCoOrdinators/SalesCoOrdinatorModel.js";

export const isAuthenticatedSalesCoOrdinator = async (req, res, next) => {
  try {
    if (!req.headers.authorization) {
      return res.status(401).json({
        success: false,
        message: "Please login to access this resource",
      });
    }
    const getToken = req.headers.authorization;
    const token = getToken.slice(7);

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    if (!decoded) {
      return res.status(400).json({
        success: false,
        message: "Incorrect token",
      });
    }
    const salescoordinator = await SalesCoOrdinator.findById(decoded.id);
    if (salescoordinator) {
      req.user = salescoordinator;
      req.userType = "SalesCoOrdinator";
      return next();
    } else {
      return res.status(401).json({
        success: false,
        message: "Unauthorized",
      });
    }
  } catch (error) {
    if (error.name === "TokenExpiredError") {
      return res.status(401).json({ message: "Token has expired." });
    } else if (error.name === "JsonWebTokenError") {
      return res.status(401).json({ message: "Invalid token." });
    } else {
      return res.status(500).json({
        message: "An internal error occurred while verifying the token.",
      });
    }
  }
};
