const { Op } = require("sequelize");
const OrderForm = require("../models/OrderForm");
const AutomationServicesLogs = require("../models/AutomationServicesLogs");
const schedule = require("node-schedule");
const sequelizeConnect = require("../connection/db");

async function triggerExpiredOrders() {
  const transaction = await sequelizeConnect.transaction();

  try {
    const includedStatus = [
      "Verified",
      "Release Order - Delivery",
      "For Preparation",
      "For Delivery",
      "For Delivery - Warehouse",
    ];

    const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);

    const expiredOrders = await OrderForm.findAll({
      where: {
        shipping_type: "Standard Shipping",
        status: {
          [Op.in]: includedStatus,
        },
        date_created: {
          [Op.lte]: sevenDaysAgo,
        },
      },
      attributes: ["id", "reference_no"],
      transaction,
      lock: transaction.LOCK.UPDATE,
    });

    if (!expiredOrders.length) {
      await transaction.commit();
      return;
    }

    const orderIds = expiredOrders.map((o) => o.id);
    const referenceNumbers = expiredOrders.map((o) => o.reference_no);

    await OrderForm.update(
      {
        status: "Release Order - Expired",
      },
      {
        where: {
          id: {
            [Op.in]: orderIds,
          },
        },
        transaction,
      },
    );

    await AutomationServicesLogs.create(
      {
        automation_type: `Expired Orders - ${referenceNumbers.join(", ")}`,
        is_success: true,
      },
      { transaction },
    );

    await transaction.commit();
  } catch (err) {
    await transaction.rollback();

    await AutomationServicesLogs.create({
      automation_type: "Expired Orders - FAILED",
      is_success: false,
    });

    throw err;
  }
}

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

module.exports = deliveredOrdersAutomation;
