const { Op, Sequelize } = require("sequelize");
const Customers = require("../models/Customers");
const OrderForm = require("../models/OrderForm");
const { filterAndFormatPhones } = require("../helpers/common");
const whispir = require("../helpers/whispir");
const MessagesLogs = require("../models/MessagesLogs");
const InactiveCustomerTextMsgHistory = require("../models/InactiveCustomerTextMsgHistory");
const AutomationServicesLogs = require("../models/AutomationServicesLogs");
const schedule = require("node-schedule");
const TriggerDeliveredOrders = require("../models/TriggerDeliveredOrders");

async function triggerDeliveredOrders() {
  try {
    const triggeredOrders = await TriggerDeliveredOrders.findAll({
      where: {
        triggered: false,
      },
    });

    for (const order of triggeredOrders) {
      const agentPromise = Customers.findOne({
        where: {
          agent_code: order.agent_code,
        },
      });
      const orderFormPromise = OrderForm.findOne({
        where: {
          id: order.order_id,
        },
        attributes: ["id", "name", "reference_no"],
      });

      const [agent, orderForm] = await Promise.all([
        agentPromise,
        orderFormPromise,
      ]);

      if (agent && agent.agent_code && agent.phone && orderForm) {
        const receiverPhoneNumbers = filterAndFormatPhones([agent.phone]);
        const agentName = `${agent.agent_code} - ${agent.first_name} ${agent.last_name}`;
        const messageContent = `Hi ${agentName}, ${orderForm.reference_no} has been delivered. Please follow up with the customer.`;

        order.triggered = true;
        order.triggered_at = new Date();
        await order.save();

        const whispirText = await whispir.messaging.singleMessage(
          {
            recipientNumber: receiverPhoneNumbers.join(","),
            customTemplate: messageContent,
          },
          "custom",
        );

        await MessagesLogs.create({
          customer_id: agent.id,
          type: "Agent Order Notification",
          receiver: receiverPhoneNumbers.join(","),
          content: messageContent,
          is_sent: whispirText ? true : false,
        });

        await AutomationServicesLogs.create({
          automation_type: `Trigger Delivered Orders - ${orderForm.reference_no}`,
          is_success: whispirText ? true : false,
        });
      }
    }
  } catch (err) {
    throw err;
  }
}

const deliveredOrdersAutomation = schedule.scheduleJob("*/5 * * * *", async () => {
  await triggerDeliveredOrders();
});

module.exports = deliveredOrdersAutomation;


// For Demo Only
// const deliveredOrdersAutomation = schedule.scheduleJob("* * * * * *", async () => {
//   await triggerDeliveredOrders();
// });

// module.exports = deliveredOrdersAutomation;