const AgentCustomer = require("../../models/AgentCustomer");
const Customers = require("../../models/Customers");

exports.addAgentCustomer = async (req, res, next) => {
  const { customerId } = req;
  const { agent_code } = req.body;

  try {
    const agent = await Customers.findOne({
      where: {
        agent_code,
        type: "Agent",
      },
    });

    if (!agent) res.status(400).json({ success: false, message: "Invalid agent code" });

    const createdAgentCustomerRelation = await AgentCustomer.create({
      agent: agent_code,
      customer: customerId,
    });

    res
      .status(201)
      .json({
        success: true,
        message: "Agent customer relation created.",
        agent_relation: createdAgentCustomerRelation,
      });
  } catch (err) {
    next(err);
  }
};
