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

export const isAuthenticated_SC_TM = 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",
      });
    }

    let user = await SalesCoOrdinator.findById(decoded.id);
    if (user) {
      req.user = user;
      req.userType = "SalesCoOrdinator";
    } else {
      user = await TerritoryManager.findById(decoded.id);
      if (user) {
        req.user = user;
        req.userType = "TerritoryManager";
      }
    }

    if (!user) {
      return res.status(401).json({
        success: false,
        message: "Unauthorized",
      });
    }

    return next();
  } 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.",
      });
    }
  }
};
