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

exports.createAgentCustomer = async (req, res, next) => {
  try {
    const { customerIds } = req.body;

    // Check if exactly two customer IDs are provided
    if (!customerIds || customerIds.length !== 2) {
      return res
        .status(400)
        .json({ error: "Exactly two customer IDs are required." });
    }

    const [customerId1, customerId2] = customerIds;

    // Retrieve customer data from the database
    const [customerData1, customerData2] = await Promise.all([
      Customers.findByPk(customerId1),
      Customers.findByPk(customerId2),
    ]);

    // Check if customer data is found for both IDs
    if (!customerData1 || !customerData2) {
      return res.status(400).json({ error: "Customer data not found." });
    }

    // Check if one is an Agent and the other is a Buyer
    if (
      (customerData1.type === "Agent" && customerData2.type === "Buyer") ||
      (customerData1.type === "Buyer" && customerData2.type === "Agent")
    ) {
      // Fetch agent_code of the agent from Customers model
      const agentCode =
        customerData1.type === "Agent"
          ? customerData1.agent_code
          : customerData2.agent_code;

      // Create relationship in the AgentCustomer model
      await AgentCustomer.create({
        agent: agentCode,
        customer: customerData1.type === "Buyer" ? customerId1 : customerId2,
      });

      return res
        .status(201)
        .json({ success: true, message: "Successfully created!" });
    } else {
      return res.status(400).json({
        success: false,
        message: "Exactly one Agent and one Buyer are required.",
      });
    }
  } catch (err) {
    next(err);
  }
};

exports.getAllAgents = (req, res, next) => {
  Customers.findAll({
    where: {
      type: "Agent",
    },
  })
    .then((agent) => {
      const agents = agent.map((agent) => ({
        id: agent.id,
        code: agent.agent_code,
        name: `${agent.first_name} ${agent.last_name}`,
      }));
      return res.status(200).json({ success: true, agents });
    })
    .catch((err) => {
      next(err);
    });
};

exports.getAllCustomerByAgentCode = (req, res, next) => {
  const { customerId } = req;

  Customers.findByPk(customerId)
    .then((customer) => {
      const { agent_code } = customer;

      return AgentCustomer.findAll({
        where: {
          agent: agent_code,
        },
        include: [
          {
            model: Customers,
            as: "customerAgent",
            attributes: {
              exclude: agentCustomerDetailsExcludes(),
            },
          },
        ],
        attributes: {
          exclude: ["customer"],
        },
      });
    })
    .then((customerAgents) => {
      res.status(200).json({ success: true, customerAgents });
    })
    .catch((err) => {
      next(err);
    });
};
