import moment from "moment";
import CONSTANTS from "../../config/constants";
import autopayQueueDB from "./autopay.model";
import recurringExpenseDB from "../../models/recurringExpense.model";
import { autopayLog } from "../serviceLog";

async function updateQueue() {
  const C = "Autopay Update";
  const F = "updateQueue";

  try {
    autopayLog.info(`[${C}], [${F}], Starting Update Queue`);

    const autopays = await autopayQueueDB.getTodayPendingAutopays();

    autopayLog.info(`[${C}], [${F}], Autopays [${JSON.stringify(autopays)}]`);

    if (autopays && autopays.length > 0) {
      for (const autopay of autopays) {
        await autopayQueueDB.addTransactionInQueue({
          clientId: autopay.clientId,
          beneficiaryId: autopay.beneficiaryId,
          amount: autopay.amount,
          status: CONSTANTS.AUTOPAY_QUEUE_STATUS.PENDING,
          description: null,
          dueDate: autopay.nextDueDate,
          autopayId: autopay.id,
        });

        let incrementPeriod = "month";
        if (autopay.frequencyType === CONSTANTS.AUTOPAY_FREQUENCY_TYPES.DAILY) {
          incrementPeriod = "day";
        } else if (
          autopay.frequencyType === CONSTANTS.AUTOPAY_FREQUENCY_TYPES.WEEKLY
        ) {
          incrementPeriod = "week";
        } else if (
          autopay.frequencyType === CONSTANTS.AUTOPAY_FREQUENCY_TYPES.MONTHLY
        ) {
          incrementPeriod = "month";
        } else if (
          autopay.frequencyType === CONSTANTS.AUTOPAY_FREQUENCY_TYPES.YEARLY
        ) {
          incrementPeriod = "year";
        }

        let newDueDate = moment(autopay.nextDueDate)
          .add(autopay.frequencyValue, incrementPeriod)
          .format("YYYY-MM-DD");

        await autopayQueueDB.updateNextDueDate({
          id: autopay.id,
          nextDueDate: newDueDate,
        });

        if (
          autopay?.totalTransactions &&
          Number(autopay?.totalTransactions) > 0
        ) {
          await autopayQueueDB.updateQueueRecordRemainingTransactions({
            id: autopay?.id,
            transactionsRemaining: autopay?.transactionsRemaining - 1,
          });

          if (Number(autopay?.transactionsRemaining - 1) <= 0) {
            await autopayQueueDB.updateAutopayMandateStatus({
              id: autopay?.id,
              status: CONSTANTS.AUTOPAY_STATUS.COMPLETED,
            });
          }
        }
      }
    }

    autopayLog.info(`[${C}], [${F}], Update Queue Completed`);

    process.exit();
  } catch (error) {
    autopayLog.info(`[${C}], [${F}], Error [${error}]`);
    process.exit();
  }
}

updateQueue();
