import log from "../config/log";
import tenantDB from "../models/tenant.model";
import CONSTANTS from "../config/constants";
import occupancyDB from "../models/occupancy.model";
import propertyDB from "../models/property.model";
import roomDB from "../models/room.model";
import duesDB from "../models/dues.model";
import generateTransId from "./generateTransId";
import createReceipt from "./createReceipt";
import moment from "moment";
import getModeName from "./getModeName";
import transactionDB from "../models/transaction.model";
import sendNotification from "./sendNotification";
import sendSMS from "./sendSMS";
import clientDB from "../models/client.model";
import ledgerDB from "../models/ledger.model";
import getDueDescription from "./getDueDescription";
import moveOutDuesDB from "../models/moveOutDues.model";
import moveOutDB from "../models/moveOut.model";
import addTransactions, { addTransactionsMoveOut } from "./addTransaction";

const adjustExcessPayments = async ({
  tenantId,
  clientId,
  ledgerReferenceId,
  amountPaid,
}: any) => {
  try {
    const tenant = await tenantDB.getById({ id: tenantId });
    const client = await clientDB.getById({ id: clientId });
    const occupancy = await occupancyDB.getByTenantIdAndClientId({ tenantId: tenantId, clientId: clientId });
    const property = await propertyDB.getById({ id: occupancy.propId });
    const room = await roomDB.getById({ id: occupancy.roomId });

    let dueDescription = '';
    if(occupancy.status == CONSTANTS.OCCUPANCY_STATUS.MOVING_OUT) {
      dueDescription = "Adjusted from security deposit during eviction.";
    }
    else{
      dueDescription = "Adjustment from previous overpayment";
    }

    const securityAdjustEntry = await ledgerDB.getLastEntry({
      tenantId,
      clientId,
    });

    let isTransactionRecorded = false;
    let amtPaid = amountPaid;
    let allDues = await duesDB.getByTenantIdAndLedgerReferenceId({
      tenantId,
      ledgerReferenceId,
    });
    // log.info(
    //   `adjustExcessPayments: amountPaid: ${amountPaid}`
    // );
    let count = 1;
    let lengthOfDues = allDues.length;
    let security = await allDues.find(
      (due: any) => due.type === CONSTANTS.DUES_TYPES.SECURITY
    );
    let receipts = [];

    if (security && security.balance > 0) {
      let due = security;
      // dueDescription = getDueDescription (due.type);
      if (security.balance <= amtPaid) {
        if (count == lengthOfDues) {
          await ledgerDB.add({
            tenantId,
            roomId: occupancy.roomId,
            propId: occupancy.propId,
            clientId: occupancy.clientId,
            amount: -due.balance,
            balance: securityAdjustEntry === false ? -(amtPaid - due.balance) : 0,
            referenceId: ledgerReferenceId,
            transactionId: null,
            type: due.type,
            rentStartDate: null,
            rentEndDate: null,
            dueDate: due.dueDate || moment().format("YYYY-MM-DD HH:mm:ss"),
            description: dueDescription,
            title: due?.title || null,
          });
          amtPaid = 0;
        } else {
          await ledgerDB.add({
            tenantId,
            roomId: occupancy.roomId,
            propId: occupancy.propId,
            clientId: occupancy.clientId,
            amount: -due.balance,
            balance: 0,
            referenceId: ledgerReferenceId,
            transactionId: null,
            type: due.type,
            rentStartDate: null,
            rentEndDate: null,
            dueDate: due.dueDate || moment().format("YYYY-MM-DD HH:mm:ss"),
            description: dueDescription,
            title: due?.title || null,
          });
          amtPaid -= due.balance;
        }
        await duesDB.removeDue({ id: due.id });
        isTransactionRecorded = true;
      } else if (security.balance > amtPaid) {
        await ledgerDB.add({
          tenantId,
          roomId: occupancy.roomId,
          propId: occupancy.propId,
          clientId: occupancy.clientId,
          amount: -amtPaid,
          balance: due.balance - amtPaid,
          referenceId: ledgerReferenceId,
          transactionId: null,
          type: due.type,
          rentStartDate: null,
          rentEndDate: null,
          dueDate: due.dueDate || moment().format("YYYY-MM-DD HH:mm:ss"),
          description: dueDescription,
          title: due?.title || null,
        });
        await duesDB.updateBalance({
          id: due.id,
          balance: due.balance - amtPaid,
        });
        amtPaid = 0;
        isTransactionRecorded = true;
      }
      count++;
    }

    if (amtPaid != 0) {
      for (const due of allDues) {
        if (amtPaid == 0) break;
        if (due.type === CONSTANTS.DUES_TYPES.SECURITY) {
          continue;
        }
        // dueDescription = getDueDescription (due.type);
        if (amtPaid <= due.balance) {
          let transId = null;
          if (occupancy.status === CONSTANTS.OCCUPANCY_STATUS.MOVING_OUT) {
            transId = await addTransactions({
              due: due,
              clientId: clientId,
              tenantId: tenantId,
              amount: amtPaid,
              description: `${getDueDescription(due.type)} (Adjusted from security)`,
              mode: CONSTANTS.TRANSACTION_MODES.ADJUSTED_FROM_SECURITY,
              recordedBy: "Auto Adjusted",
              duesStatsArr: [
                { title: dueDescription, amount: amtPaid },
              ],
            });
          }

          await ledgerDB.add({
            tenantId,
            roomId: occupancy.roomId,
            propId: occupancy.propId,
            clientId: occupancy.clientId,
            amount: -amtPaid,
            balance: due.balance - amtPaid,
            referenceId: ledgerReferenceId,
            transactionId: transId || null,
            type: due.type,
            rentStartDate: due.rentStartDate || null,
            rentEndDate: due.rentEndDate || null,
            dueDate: due.dueDate || moment().format("YYYY-MM-DD HH:mm:ss"),
            description: due.discount > 0 
              ? amtPaid === due.balance 
                ? `${dueDescription}, Discount of ₹${due.discount} given for this due` 
                : dueDescription 
              : dueDescription,
            discount: due.discount,
            title: due?.title || null,
            subType: occupancy.status === CONSTANTS.OCCUPANCY_STATUS.MOVING_OUT ? CONSTANTS.LEDGER_SUBTYPES.MARKED_FROM_SECURITY : 0,
          });
          if (amtPaid == due.balance) {
            await duesDB.removeDue({ id: due.id });
          } else {
            await duesDB.updateBalance({
              id: due.id,
              balance: due.balance - amtPaid,
            });
          }
          amtPaid = 0;
        } else {
          let transId = null;
          if (occupancy.status === CONSTANTS.OCCUPANCY_STATUS.MOVING_OUT) {
            transId = await addTransactions({
              due: due,
              clientId: clientId,
              tenantId: tenantId,
              amount: due.balance,
              description: `${getDueDescription(due.type)} (Adjusted from security)`,
              mode: CONSTANTS.TRANSACTION_MODES.ADJUSTED_FROM_SECURITY,
              recordedBy: "Auto Adjusted",
              duesStatsArr: [
                { title: dueDescription, amount: amtPaid },
              ],
            });
          }

          if (count == lengthOfDues) {
            amtPaid -= due.balance;
            await ledgerDB.add({
              tenantId,
              roomId: occupancy.roomId,
              propId: occupancy.propId,
              clientId: occupancy.clientId,
              amount: -due.balance,
              balance: securityAdjustEntry === false ? -amtPaid : 0,
              referenceId: ledgerReferenceId,
              transactionId: transId || null,
              type: due.type,
              rentStartDate: null,
              rentEndDate: null,
              dueDate: due.dueDate || moment().format("YYYY-MM-DD HH:mm:ss"),
              description: due.discount > 0 ? `${dueDescription}, Discount of ₹${due.discount} given for this due` : dueDescription,
              discount: due.discount,
              title: due?.title || null,
              subType: occupancy.status === CONSTANTS.OCCUPANCY_STATUS.MOVING_OUT ? CONSTANTS.LEDGER_SUBTYPES.MARKED_FROM_SECURITY : 0,
            });
            //break;
          } else {
            await ledgerDB.add({
              tenantId,
              roomId: occupancy.roomId,
              propId: occupancy.propId,
              clientId: occupancy.clientId,
              amount: -due.balance,
              balance: 0,
              referenceId: ledgerReferenceId,
              transactionId: null,
              type: due.type,
              rentStartDate: null,
              rentEndDate: null,
              dueDate: due.dueDate || moment().format("YYYY-MM-DD HH:mm:ss"),
              description: due.discount > 0 ? `${dueDescription}, Discount of ₹${due.discount} given for this due` : dueDescription,
              discount: due.discount,
              title: due?.title || null,
              subType: occupancy.status === CONSTANTS.OCCUPANCY_STATUS.MOVING_OUT ? CONSTANTS.LEDGER_SUBTYPES.MARKED_FROM_SECURITY : 0,
            });
            amtPaid -= due.balance;
          }
          await duesDB.removeDue({ id: due.id });
        }
        isTransactionRecorded = true;
        count++;
      }
    }

    if (securityAdjustEntry !== false && amtPaid > 0) {
      await ledgerDB.removeById({
        id: securityAdjustEntry.id,
      });

      //creating new security entry after deleting previous
      await ledgerDB.add({
        tenantId: securityAdjustEntry.tenantId,
        roomId: securityAdjustEntry.roomId,
        propId: securityAdjustEntry.propId,
        clientId: clientId,
        amount: securityAdjustEntry.amount,
        balance: -amtPaid,
        referenceId: securityAdjustEntry.referenceId,
        transactionId: securityAdjustEntry.transactionId,
        type: securityAdjustEntry.type,
        rentStartDate: securityAdjustEntry.rentStartDate,
        rentEndDate: securityAdjustEntry.rentEndDate,
        description: securityAdjustEntry.description,
        dueDate: securityAdjustEntry.dueDate,
      });
    }
    
    if (isTransactionRecorded && amtPaid > 0) {
      let isNotiSent = false;
      if (tenant.regId) {
        isNotiSent = await sendNotification({
          title: `Adjusted previous balance ₹${amountPaid} for due payments`,
          message: `Thank you for paying for your due payments timely.`,
          regId: tenant.regId,
          userId: tenant.id,
          userType: CONSTANTS.USER_TYPE.TENANT,
          notiCategory: CONSTANTS.NOTIFICATION_CATEGORY.EXCESS_PAYMENT,
          clientId: client.id,
        });
      }

      const msg = CONSTANTS.MSG.DUE_PAID.replace(
        "{#var#}",
        tenant.name
      ).replace("{#var2#}", amountPaid.toString());

      const isSent = await sendSMS(
        tenant.mobile,
        msg,
        CONSTANTS.SMS_TEMPLATE_IDS.DUE_PAID
      );
    }

    if (!isTransactionRecorded) {
      return "No Dues Found";
    }

    return "Transaction Recorded Successfully";
  } catch (error: any) {
    return `Error: ${error?.message || error}`;
  }
};

// export const adjustExcessPaymentsForMovedOut = async ({
//   tenantId,
//   clientId,
//   ledgerReferenceId,
//   amountPaid,
// }: any) => {
//   try {
//     const tenant = await tenantDB.getById({ id: tenantId });
//     const occupancy = await moveOutDB.getByTenantIdAndClientId({ 
//       clientId: clientId,
//       tenantId: tenantId,
//     });

//     let dueDescription = '';
//     if(occupancy.status == CONSTANTS.OCCUPANCY_STATUS.MOVING_OUT) {
//       dueDescription = "Adjusted from security deposit during eviction.";
//     }
//     else{
//       dueDescription = "Adjustment from previous overpayment";
//     }

//     let isTransactionRecorded = false;
//     let amtPaid = amountPaid;
//     let allDues = await moveOutDuesDB.getByTenantIdAndLedgerReferenceId({
//       tenantId,
//       ledgerReferenceId,
//     });
//     // log.info(
//     //   `adjustExcessPayments: amountPaid: ${amountPaid}`
//     // );
//     let count = 1;
//     let lengthOfDues = allDues.length;

//     if (amtPaid != 0) {
//       for (const due of allDues) {
//         if (amtPaid == 0) break;
//         // dueDescription = getDueDescription (due.type);
//         if (amtPaid <= due.balance) {
//           await ledgerDB.add({
//             tenantId,
//             roomId: occupancy.roomId,
//             propId: occupancy.propId,
//             clientId: occupancy.clientId,
//             amount: -amtPaid,
//             balance: due.balance - amtPaid,
//             referenceId: ledgerReferenceId,
//             transactionId: null,
//             type: due.type,
//             rentStartDate: null,
//             rentEndDate: null,
//             dueDate: due.dueDate || moment().format("YYYY-MM-DD HH:mm:ss"),
//             description: due.discount > 0 
//               ? amtPaid === due.balance 
//                 ? `${dueDescription}, Discount of ₹${due.discount} given for this due` 
//                 : dueDescription
//               : dueDescription,
//             discount: due.discount,
//             title: due?.title || null,
//           });
//           if (amtPaid == due.balance) {
//             await moveOutDuesDB.removeDue({ id: due.id });
//             await moveOutDB.subtractTenantDue({
//               clientId: occupancy.clientId,
//               tenantId,
//               tenantDues: due.balance,
//               propId: occupancy.propId,
//               roomId: occupancy.roomId,
//             });
//           } else {
//             await moveOutDuesDB.updateBalance({
//               id: due.id,
//               balance: due.balance - amtPaid,
//             });
//             await moveOutDB.subtractTenantDue({
//               clientId: occupancy.clientId,
//               tenantId,
//               tenantDues: amtPaid,
//               propId: occupancy.propId,
//               roomId: occupancy.roomId,
//             });
//           }
//           amtPaid = 0;
//         } else {
//           if (count == lengthOfDues) {
//             amtPaid -= due.balance;
//             await ledgerDB.add({
//               tenantId,
//               roomId: occupancy.roomId,
//               propId: occupancy.propId,
//               clientId: occupancy.clientId,
//               amount: -due.balance,
//               balance: -amtPaid,
//               referenceId: ledgerReferenceId,
//               transactionId: null,
//               type: due.type,
//               rentStartDate: null,
//               rentEndDate: null,
//               dueDate: due.dueDate || moment().format("YYYY-MM-DD HH:mm:ss"),
//               description: due.discount > 0 ? `${dueDescription}, Discount of ₹${due.discount} given for this due` : dueDescription,
//               discount: due.discount,
//               title: due?.title || null,
//             });
//             //break;
//           } else {
//             await ledgerDB.add({
//               tenantId,
//               roomId: occupancy.roomId,
//               propId: occupancy.propId,
//               clientId: occupancy.clientId,
//               amount: -due.balance,
//               balance: 0,
//               referenceId: ledgerReferenceId,
//               transactionId: null,
//               type: due.type,
//               rentStartDate: null,
//               rentEndDate: null,
//               dueDate: due.dueDate || moment().format("YYYY-MM-DD HH:mm:ss"),
//               description: due.discount > 0 ? `${dueDescription}, Discount of ₹${due.discount} given for this due` : dueDescription,
//               discount: due.discount,
//               title: due?.title || null,
//             });
//             amtPaid -= due.balance;
//           }
//           await moveOutDuesDB.removeDue({ id: due.id });
//           await moveOutDB.subtractTenantDue({
//             clientId: occupancy.clientId,
//             tenantId,
//             tenantDues: due.balance,
//             propId: occupancy.propId,
//             roomId: occupancy.roomId,
//           });
//         }
//         isTransactionRecorded = true;
//         count++;
//       }
//     }
    
//     if (isTransactionRecorded && amtPaid > 0) {
//       let isNotiSent = false;
//       if (tenant.regId) {
//         isNotiSent = await sendNotification({
//           title: `Adjusted previous balance ₹${amountPaid} for due payments`,
//           message: `Thank you for paying for your due payments timely.`,
//           regId: tenant.regId,
//           userId: tenant.id,
//           userType: CONSTANTS.USER_TYPE.TENANT,
//           notiCategory: CONSTANTS.NOTIFICATION_CATEGORY.EXCESS_PAYMENT,
//           clientId: clientId,
//         });
//       }

//       const msg = CONSTANTS.MSG.DUE_PAID.replace(
//         "{#var#}",
//         tenant.name
//       ).replace("{#var2#}", amountPaid.toString());

//       const isSent = await sendSMS(
//         tenant.mobile,
//         msg,
//         CONSTANTS.SMS_TEMPLATE_IDS.DUE_PAID
//       );
//     }

//     if (!isTransactionRecorded) {
//       return "No Dues Found";
//     }

//     return "Transaction Recorded Successfully";
//   } catch (error: any) {
//     return `Error: ${error?.message || error}`;
//   }
// };

export const adjustExcessPaymentsForMovedOutX = async ({
  tenantId,
  clientId,
  ledgerReferenceId,
  amountPaid,
  markedFromSecurity = 0,
  recordedBy = "",
}: any) => {
  try {

    const securityAdjustEntry = await ledgerDB.getLastEntry({
      tenantId,
      clientId,
    });

    const tenant = await tenantDB.getById({ id: tenantId });
    const occupancy = await moveOutDB.getByTenantIdAndClientId({ 
      clientId: clientId,
      tenantId: tenantId,
    });

    let dueDescription = 'Adjusted from security';
    // if(occupancy.status == CONSTANTS.OCCUPANCY_STATUS.MOVING_OUT) {
    //   dueDescription = "Adjusted from security deposit during eviction.";
    // }
    // else{
    //   dueDescription = "Adjustment from previous overpayment";
    // }

    let isTransactionRecorded = false;
    let amtPaid = amountPaid;
    let allDues = await moveOutDuesDB.getByTenantIdAndLedgerReferenceId({
      tenantId,
      ledgerReferenceId,
    });
    // log.info(
    //   `adjustExcessPayments: amountPaid: ${amountPaid}`
    // );
    let count = 1;
    let lengthOfDues = allDues.length;

    if (amtPaid != 0) {
      for (const due of allDues) {
        const transDescription = await getDueDescription(due.type);
        if (amtPaid == 0) break;
        // dueDescription = getDueDescription (due.type);
        if (amtPaid <= due.balance) {
          let transId = null;
          if (markedFromSecurity === 1) {
            transId = await addTransactionsMoveOut({
              due: due,
              clientId: clientId,
              tenantId: tenantId,
              amount: amtPaid,
              description: `${transDescription}(Adjusted from security)`,
              mode: CONSTANTS.TRANSACTION_MODES.ADJUSTED_FROM_SECURITY,
              // recordedBy: recordedBy || "",
              recordedBy: "Kipinn",
              duesStatsArr: [
                { title: transDescription, amount: amtPaid },
              ]
            });
          }
          await ledgerDB.add({
            tenantId,
            roomId: occupancy.roomId,
            propId: occupancy.propId,
            clientId: occupancy.clientId,
            amount: -amtPaid,
            balance: due.balance - amtPaid,
            referenceId: ledgerReferenceId,
            transactionId: transId || null,
            type: due.type,
            rentStartDate: due?.rentStartDate,
            rentEndDate: due?.rentEndDate,
            dueDate: due.dueDate || moment().format("YYYY-MM-DD HH:mm:ss"),
            description: due.discount > 0 
              ? amtPaid === due.balance 
                ? `${dueDescription}, Discount of ₹${due.discount} given for this due` 
                : dueDescription
              : dueDescription,
            discount: due.discount,
            title: due?.title || null,
            subType: markedFromSecurity === 1 ? CONSTANTS.LEDGER_SUBTYPES.MARKED_FROM_SECURITY : 0,
          });
          if (amtPaid == due.balance) {
            await moveOutDuesDB.removeDue({ id: due.id });
            await moveOutDB.subtractTenantDue({
              clientId: occupancy.clientId,
              tenantId,
              tenantDues: due.balance,
              propId: occupancy.propId,
              roomId: occupancy.roomId,
            });
          } else {
            await moveOutDuesDB.updateBalance({
              id: due.id,
              balance: due.balance - amtPaid,
            });
            await moveOutDB.subtractTenantDue({
              clientId: occupancy.clientId,
              tenantId,
              tenantDues: amtPaid,
              propId: occupancy.propId,
              roomId: occupancy.roomId,
            });
          }
          // if (markedFromSecurity === 1) {
          //   const transId = await addTransactionsMoveOut({
          //     due: due,
          //     clientId: clientId,
          //     tenantId: tenantId,
          //     amount: amtPaid,
          //     description: `${transDescription}(Adjusted from security)`,
          //     mode: CONSTANTS.TRANSACTION_MODES.ADJUSTED_FROM_SECURITY,
          //     // recordedBy: recordedBy || "",
          //     recordedBy: "Kipinn",
          //     duesStatsArr: [
          //       { title: transDescription, amount: amtPaid },
          //     ]
          //   });
          // }
          amtPaid = 0;
        } else {
          let transId = null;
          if (markedFromSecurity === 1) {
            transId = await addTransactionsMoveOut({
              due: due,
              clientId: clientId,
              tenantId: tenantId,
              amount: due.balance,
              description: `${transDescription}(Adjusted from security)`,
              mode: CONSTANTS.TRANSACTION_MODES.ADJUSTED_FROM_SECURITY,
              recordedBy: "Kipinn",
              duesStatsArr: [
                { title: transDescription, amount: due.balance },
              ]
            });
          }
          if (count == lengthOfDues) {
            amtPaid -= due.balance;
            await ledgerDB.add({
              tenantId,
              roomId: occupancy.roomId,
              propId: occupancy.propId,
              clientId: occupancy.clientId,
              amount: -due.balance,
              balance: securityAdjustEntry === false ? -amtPaid : 0,
              referenceId: ledgerReferenceId,
              transactionId: transId || null,
              type: due.type,
              rentStartDate: due?.rentStartDate,
              rentEndDate: due?.rentEndDate,
              dueDate: due.dueDate || moment().format("YYYY-MM-DD HH:mm:ss"),
              description: due.discount > 0 ? `${dueDescription}, Discount of ₹${due.discount} given for this due` : dueDescription,
              discount: due.discount,
              title: due?.title || null,
              subType: markedFromSecurity === 1 ? CONSTANTS.LEDGER_SUBTYPES.MARKED_FROM_SECURITY : 0,
            });
            //break;
          } else {
            await ledgerDB.add({
              tenantId,
              roomId: occupancy.roomId,
              propId: occupancy.propId,
              clientId: occupancy.clientId,
              amount: -due.balance,
              balance: 0,
              referenceId: ledgerReferenceId,
              transactionId: transId || null,
              type: due.type,
              rentStartDate: due?.rentStartDate,
              rentEndDate: due?.rentEndDate,
              dueDate: due.dueDate || moment().format("YYYY-MM-DD HH:mm:ss"),
              description: due.discount > 0 ? `${dueDescription}, Discount of ₹${due.discount} given for this due` : dueDescription,
              discount: due.discount,
              title: due?.title || null,
              subType: markedFromSecurity === 1 ? CONSTANTS.LEDGER_SUBTYPES.MARKED_FROM_SECURITY : 0,
            });
            amtPaid -= due.balance;
          }

          // if (markedFromSecurity === 1) {
          //   const transId = await addTransactionsMoveOut({
          //     due: due,
          //     clientId: clientId,
          //     tenantId: tenantId,
          //     amount: due.balance,
          //     description: `${transDescription}(Adjusted from security)`,
          //     mode: CONSTANTS.TRANSACTION_MODES.ADJUSTED_FROM_SECURITY,
          //     recordedBy: "Kipinn",
          //     duesStatsArr: [
          //       { title: transDescription, amount: due.balance },
          //     ]
          //   });
          // }

          await moveOutDuesDB.removeDue({ id: due.id });
          await moveOutDB.subtractTenantDue({
            clientId: occupancy.clientId,
            tenantId,
            tenantDues: due.balance,
            propId: occupancy.propId,
            roomId: occupancy.roomId,
          });
        }
        isTransactionRecorded = true;
        count++;
      }
    }

    if (securityAdjustEntry !== false && amtPaid > 0) {
      await ledgerDB.removeById({
        id: securityAdjustEntry.id,
      });

      //creating new security entry after deleting previous
      await ledgerDB.add({
        tenantId: securityAdjustEntry.tenantId,
        roomId: securityAdjustEntry.roomId,
        propId: securityAdjustEntry.propId,
        clientId: clientId,
        amount: securityAdjustEntry.amount,
        balance: -amtPaid,
        referenceId: securityAdjustEntry.referenceId,
        transactionId: securityAdjustEntry.transactionId,
        type: securityAdjustEntry.type,
        rentStartDate: securityAdjustEntry.rentStartDate,
        rentEndDate: securityAdjustEntry.rentEndDate,
        description: securityAdjustEntry.description,
        dueDate: securityAdjustEntry.dueDate,
      });
    } else if (securityAdjustEntry !== false && amtPaid <= 0) {
      let newDescription = securityAdjustEntry.description.replace(/Refund after eviction/i, "Fully Adjusted In Due").trim();
      await ledgerDB.updateDescription({
        id: securityAdjustEntry?.id,
        description: newDescription,
      });
    }
    
    if (isTransactionRecorded && amtPaid > 0) {
      let isNotiSent = false;
      if (tenant.regId) {
        isNotiSent = await sendNotification({
          title: `Adjusted previous balance ₹${amountPaid} for due payments`,
          message: `Thank you for paying for your due payments timely.`,
          regId: tenant.regId,
          userId: tenant.id,
          userType: CONSTANTS.USER_TYPE.TENANT,
          notiCategory: CONSTANTS.NOTIFICATION_CATEGORY.EXCESS_PAYMENT,
          clientId: clientId,
        });
      }

      const msg = CONSTANTS.MSG.DUE_PAID.replace(
        "{#var#}",
        tenant.name
      ).replace("{#var2#}", amountPaid.toString());

      const isSent = await sendSMS(
        tenant.mobile,
        msg,
        CONSTANTS.SMS_TEMPLATE_IDS.DUE_PAID
      );
    }

    if (!isTransactionRecorded) {
      return "No Dues Found";
    }

    return "Transaction Recorded Successfully";
  } catch (error: any) {
    return `Error: ${error?.message || error}`;
  }
};

export default adjustExcessPayments;
