const Sequelize = require("sequelize");
const schedule = require("node-schedule");

const BuildCreditPayments = require("../models/RpafPayment");
const PdcHistory = require("../models/PdcHistory");
const BuildcreditOverPayments = require("../models/BuildcreditOverPayments");
const AutomationServicesLogs = require("../models/AutomationServicesLogs");

async function updatePdcPayments() {
  try {
    const oneDayAgo = new Date();
    oneDayAgo.setDate(oneDayAgo.getDate() - 1);

    const dueChequePayments = await BuildCreditPayments.findAll({
      where: {
        status: "PDC Received",
        is_pdc_payment: true,
        cheque_date: {
          [Sequelize.Op.lte]: oneDayAgo,
        },
      },
    });

    const dueChequeOverpayments = await BuildcreditOverPayments.findAll({
      where: {
        payment_status: "PDC Received",
        is_pdc_payment: true,
        cheque_date: {
          [Sequelize.Op.lte]: oneDayAgo,
        },
      },
    });

    const updatedIds = dueChequePayments.map((cheque) => cheque.id);
    const updatedIdsOverpayment = dueChequeOverpayments.map((cheque) => cheque.id);

    const updateBuildCreditPromises = updatedIds.map((id) => {
      return BuildCreditPayments.update(
        { status: "Verified" },
        {
          where: { id },
        }
      );
    });

    const updateBuildcreditOverPaymentPromises = updatedIdsOverpayment.map((id) => {
      return BuildcreditOverPayments.update({
        payment_status: "Verified",
        where: {
          id,
        },
      });
    });

    const updatePdcHistoryPromises = updatedIds.map((id) => {
      return PdcHistory.update(
        { cheque_verified_date: new Date() },
        {
          where: { rpaf_payment_id: id },
        }
      );
    });

    await Promise.all([
      ...updateBuildCreditPromises,
      ...updateBuildcreditOverPaymentPromises,
      ...updatePdcHistoryPromises,
    ]);

    console.log(`Updated ${updatedIds.length} records to Verified status and updated pdc_history table.`);

    await AutomationServicesLogs.create({
      automation_type: "Buildcredit PDC Payments",
      is_success: updatedIds.length > 0 ? true : false,
    });
  } catch (err) {
    console.error("Error updating PDC payments:", err);
  }
}

const automaticPdcPayments = schedule.scheduleJob("0 0 * * *", updatePdcPayments);

module.exports = automaticPdcPayments;
