const Customers = require("../models/Customers");
const BuildCredit = require("../models/Rpaf");
const { Op } = require("sequelize");
const { getBuildCreditBalance } = require("../helpers/buildcredit");
const { filterAndFormatPhones, formatDate12Hour } = require("../helpers/common");
const whispir = require("../helpers/whispir");
const MessagesLogs = require("../models/MessagesLogs");
const schedule = require("node-schedule");
const AutomationServicesLogs = require("../models/AutomationServicesLogs");

async function buildCreditBalance() {
  try {
    const buildCreditCustomersPromise = BuildCredit.findAll({
      where: {
        status: {
          [Op.notIn]: ["Draft", "Pending", "Pending - Waiting for other requirements"],
        },
      },
      include: [
        {
          model: Customers,
          as: "customer_detail",
          attributes: ["first_name", "last_name", "hardware_name", "phone", "phone_2", "phone_3"],
        },
      ],
      attributes: ["customer_id", "company_name"],
    });

    const promises = await Promise.all([buildCreditCustomersPromise]);

    const buildCreditCustomers = promises[0];

    const buildCreditCustomersAndBalances = [];
    const receiverPhoneNumbers = [];
    for (const customer of buildCreditCustomers) {
      const buildCredit = await getBuildCreditBalance(customer.customer_id, true);

      const parsedUsedCreditLimit = parseFloat(buildCredit.current_bal) || 0;

      if (parsedUsedCreditLimit === 0) continue;

      buildCreditCustomersAndBalances.push({
        customer_name: `${customer?.customer_detail?.first_name} ${customer?.customer_detail?.last_name}`,
        company_name: customer?.company_name,
        phone_number: filterAndFormatPhones([customer?.customer_detail?.phone]).join(","),
        balance: buildCredit.current_bal,
        date: formatDate12Hour(new Date()),
      });

      receiverPhoneNumbers.push(customer?.customer_detail?.phone);
    }

    const resources = await whispir.resource.createResource(buildCreditCustomersAndBalances);

    let bulkMessage = null;
    if (resources) {
      const resourceId = resources?.data?.id;

      bulkMessage = await whispir.messaging.bulkMessaging(
        { resourceId, mobile_mapping_field: "phone_number" },
        "EB7124FED390ED6A",
        "BuilCredit SMS"
      );
    }
    await MessagesLogs.create({
      customer_id: 0,
      type: "Bulk Message",
      receiver: receiverPhoneNumbers.join(","),
      content: "Build Credit Monthly Balance Text",
      is_sent: bulkMessage ? true : false,
    });

    await AutomationServicesLogs.create({
      automation_type: "BuildCredit Monthly Balance",
      is_success: bulkMessage ? true : false,
    });
  } catch (err) {
    throw err;
  }
}

const buildCreditBalanceJob = schedule.scheduleJob("0 13 28 * *", async function () {
  const now = new Date();
  const currentHour = now.getHours();
  const currentMinutes = now.getMinutes();
  const currentDay = now.getDate();

  if (currentHour === 13 && currentMinutes === 0 && currentDay === 28) {
    await buildCreditBalance();
  }
});

module.exports = buildCreditBalanceJob;
