const Customers = require("../../models/Customers");
const AgentCustomerList = require("../../models/AgentCustomer");
const { agentCustomerDetailsExcludes } = require("../../helpers/model-excludes-attributes/excludes");
const jwt = require("jsonwebtoken");

exports.impersonateCustomer = (req, res, next) => {
  const { customerId: userId } = req;
  const { impersonate_customer_id } = req.body;

  if (!impersonate_customer_id) {
    return res.status(500).json({ success: false, msg: "Invalid request body." });
  }
  Customers.findByPk(userId)
    .then((customer) => {
      if (!customer.type === "Agent" || customer.agent_code === null) {
        return res.status(200).json({ success: false, msg: "Invalid Agent" });
      }

      console.log(customer.agent_code);
      return AgentCustomerList.findOne({
        where: {
          agent: customer.agent_code,
          customer: impersonate_customer_id,
        },
        include: [
          {
            model: Customers,
            as: "customerAgent",
            attributes: {
              exclude: agentCustomerDetailsExcludes(),
            },
          },
        ],
      });
    })
    .then((customerInfo) => {
      if (!customerInfo) {
        return res.status(200).json({ success: false, msg: "Invalid impersonation customer id" });
      }

      const userId = customerInfo.customerAgent.id;
      const token = jwt.sign({ customerId: userId, impersonation: true }, process.env.SECRETKEY, {
        expiresIn: "7d",
      });
      res.status(200).json({ success: true, customerInfo, token });
    })
    .catch((err) => next(err));
};
