import moment from "moment";
import CONSTANTS from "../config/constants";
import log from "../config/log";
import occupanciesTypes from "../schemas/occupancy.schema";
import { calculateRentAsPerRentalType, calculateRentAsPerRentalTypeForReserved } from "./calculateRentPerDay";
import generateLedgerReferenceId from "./generateLedgerReferenceId";
import getDueDescription from "./getDueDescription";
import duesDB from "../models/dues.model";
import ledgerDB from "../models/ledger.model";

const addRentForMoveIn = async (
    clientId: number,
    tenantId: number,
    moveInDate: string,
    rentalCycle: number,
    isFutureDate: boolean,
    occupancies: [occupanciesTypes],
) => {
    const C = "addRentWhileMoveIn";
    const F = "addRentForMoveIn"

    const occupancy = occupancies[0];
    const monthlyRent = occupancy?.rent;
    const rentalType = occupancy?.rentalType;
    let dueDescription = "";
    let referenceId;
    const discountStartDate = occupancy?.discountStartDate;
    const discountEndDate = occupancy?.discountEndDate;
    let rents = [];
    if (isFutureDate) {
      rents = calculateRentAsPerRentalTypeForReserved(
        moveInDate,
        rentalCycle,
        monthlyRent,
        rentalType
      );
    } else {
      rents = calculateRentAsPerRentalType(
        moveInDate,
        rentalCycle,
        monthlyRent,
        rentalType
      );
    }
    dueDescription = getDueDescription(CONSTANTS.DUES_TYPES.RENT);

    let discountFlag = 1;

    if (Array.isArray(rents) && rents.length > 0) {
      for (let rent of rents) {
        referenceId = await generateLedgerReferenceId({ clientId });
        log.info(
          `[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Prop Id [${occupancy?.propId}], Start Date [${rent.startDate}], End Date [${rent.endDate}], Rent [${rent.rent}]`
        );

        let rentAfterDiscount = rent.rent;

        log.info(
          `[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Dicount Start Date [${discountStartDate}], Discount End Date [${discountEndDate}], Rent Start Date [${rent.startDate}] Disocunt Added`
        );

        if (
          Number(occupancies[0].discount) &&
          Number(occupancies[0].discount) > 0 &&
          moment(discountStartDate).isSameOrBefore(rent.startDate) &&
          discountFlag <= Number(occupancies[0].discountPeriod)
        ) {
          if (occupancies[0].discountType === CONSTANTS.DISCOUNT_TYPE.FLAT) {
            rentAfterDiscount = Number(rent.rent) - Number(occupancies[0].discount);
            discountFlag += 1;
          } else if (occupancies[0].discountType === CONSTANTS.DISCOUNT_TYPE.PERCENTAGE) {
            rentAfterDiscount = rent.rent - ((rent.rent * occupancies[0].discount) / 100);
            discountFlag += 1;
          }

          log.info(
            `[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Discount Type [${occupancies[0].discountType}], Discount [${occupancies[0].discount}], Rent Amount [${rent.rent}], Rent After Discount [${rentAfterDiscount}], Disocunt Added`
          );
        }

        if (rentAfterDiscount > 0) {
          await duesDB.addWithStartEndDateX({
            tenantId,
            // amount: rent.rent,
            amount: rentAfterDiscount,
            occupancyId: occupancies[0].id,
            roomId: occupancy?.roomId,
            propId: occupancy?.propId,
            clientId,
            rentStartDate: rent.startDate,
            rentEndDate: rent.endDate,
            dueDate: moment(rent.startDate).format("YYYY-MM-DD HH:mm:ss"),
            type: CONSTANTS.DUES_TYPES.RENT,
            // balance: rent.rent,
            balance: rentAfterDiscount,
            ledgerReferenceId: referenceId,
            title: "Rent",
            description: "Due added while onboarding",
            discount: rent.rent - rentAfterDiscount,
          });
          await ledgerDB.add({
            tenantId: tenantId,
            roomId: occupancy?.roomId,
            propId: occupancy?.propId,
            clientId,
            // amount: rent.rent,
            amount: rentAfterDiscount,
            // balance: rent.rent,
            balance: rentAfterDiscount,
            referenceId: referenceId,
            transactionId: null,
            type: CONSTANTS.DUES_TYPES.RENT,
            rentStartDate: rent.startDate,
            rentEndDate: rent.endDate,
            dueDate: moment(rent.startDate).format("YYYY-MM-DD HH:mm:ss"),
            //changed below description moment(---) at 17/12/2024 20:03:00
            description: rent.rent - rentAfterDiscount > 0
              ? `${dueDescription} for ${moment(rent.startDate).format("DD MMM YY")} to ${moment(rent.endDate).format("DD MMM YY")}, Discount of ₹${rent.rent - rentAfterDiscount} given for this due`
              : `${dueDescription} for ${moment(rent.startDate).format("DD MMM YY")} to ${moment(rent.endDate).format("DD MMM YY")}`,
            discount: rent.rent - rentAfterDiscount,
            title: "Rent",
          });
        }
      }
    }
    return true; 
};

export default addRentForMoveIn;