import { Response } from "express";
import moment from "moment";
import Razorpay from "razorpay";
import CONSTANTS from "../config/constants";
import log from "../config/log";
import clientDB from "../models/client.model";
import duesDB from "../models/dues.model";
import propertyDB from "../models/property.model";
import staffDB from "../models/staff.model";
import tenantDB from "../models/tenant.model";
import propertiesTypes from "../schemas/property.schema";
import CustomRequest from "../types/requestType";
import getMatchedTransactionFor from "../utils/client/getMatchedTransactionFor";
import ledgerDB from "../models/ledger.model";
import roomDB from "../models/room.model";
import occupancyDB from "../models/occupancy.model";
import transactionDB from "../models/transaction.model";
import moveOutDB from "../models/moveOut.model";
import { formatLedgerData } from "../utils/client/formatLedgerData";
import axios from "axios";
import flatDB from "../models/flat.model";
import fs from "fs";
import fsPromises from "fs/promises";
// @ts-ignore
import pdf from "pdf-creator-node";

const ledger: any = {};

ledger.ListTenantLedger = async (req: CustomRequest, res: Response) => {
  const C = "Ledger Controller";
  const F = "ListTenantLedger";

  try {
    const { pageNum, m, s, y, e = 0 } = req.query;
    const { tenantId } = req.params;
    const platform = req.platform;

    let isEvicted = e === "1";

    let clientId = req.id;
    const userType = req.userType;

    let ledger = [];
    let curMonthTransAmount = 0;
    let prevMonthTransAmount = 0;
    let diff = 0;
    let limit = 100;
    if (platform === CONSTANTS.TENANT_DEVICE_TYPE.WEB) {
      limit = 10e9;
    }

    log.info(
      `[${C}], [${F}], Client Id [${clientId}], Page Number [${pageNum}], Month [${m}], Year [${y}], Search Val [${s}], Tenant Id [${tenantId}], User Type [${userType}], Is Evicted [${isEvicted}], Platform [${platform}]`
    );

    const month = Number(m) || 0;
    const year = Number(y) || 0;

    // if (!month || month > 12 || !year) {
    //   log.info(
    //     `[${C}], [${F}], Client Id [${clientId}], Page Number [${pageNum}], Month [${month}], Year [${year}], Search Val [${s}], Not a Valid Month`
    //   );
    //   return res
    //     .status(400)
    //     .json({ msg: CONSTANTS.MSG.INVALID_REQUEST, isSuccess: false });
    // }

    // let date = moment()
    //   .month(month - 1)
    //   .year(year)
    //   .format("YYYY-MM-DD");

    if (userType === CONSTANTS.USER_TYPE.STAFF) {
      const staffId = req.id;
      const staff = await staffDB.getById({ id: staffId });
      if (!staff) {
        log.info(
          `[${C}], [${F}], Client Id [${clientId}], Page Number [${pageNum}], Month [${month}], Year [${year}], Search Val [${s}], Staff Id [${staffId}], No Staff Found`
        );
        return res
          .status(400)
          .json({ msg: CONSTANTS.MSG.INVALID_REQUEST, isSuccess: false });
      }

      log.info(
        `[${C}], [${F}], Client Id [${clientId}], Page Number [${pageNum}], Month [${month}], Year [${year}], Search Val [${s}], Staff Id [${staffId}], Staff Requested.....`
      );

      clientId = staff.clientId;
    } else {
      log.info(
        `[${C}], [${F}], Client Id [${clientId}], Page Number [${pageNum}], Month [${month}], Year [${year}], Search Val [${s}], Client Requested.....`
      );
    }

    const client = await clientDB.getById({ id: clientId });

    if (!client) {
      log.info(
        `[${C}], [${F}], Client Id [${clientId}], Page Number [${pageNum}], Month [${month}], Year [${year}], Search Val [${s}], No Client Found`
      );
      return res
        .status(400)
        .json({ msg: CONSTANTS.MSG.INVALID_REQUEST, isSuccess: false });
    }

    if (s && s !== "undefined" && s !== "null" && s !== " ") {
      const { transactionForValue } = getMatchedTransactionFor(s.toString());

      ledger = await ledgerDB.getSearchResultByTenantId({
        tenantId,
        clientId,
        pageNum: Number(pageNum),
        limit,
        searchVal: s,
        transactionForValue,
      });
    } else {
      ledger = await ledgerDB.getByTenantIdAsc({
        tenantId,
        clientId,
        pageNum: Number(pageNum),
        limit,
      });
    }

    //Sukhbir - can we remove this?
    if (ledger) {
      for (let trans of ledger) {
        trans.desc = `for the month of ${moment(trans.dueDate).format("MMM")}`;
      }
    }

    let occupancy = null;

    if (isEvicted) {
      occupancy = await moveOutDB.getByTenantIdAndClientId({
        tenantId,
        clientId,
      });
    } else {
      occupancy = await occupancyDB.getByTenantIdAndClientId({
        clientId: clientId,
        tenantId: tenantId,
      });
      if (!occupancy) {
        occupancy = await moveOutDB.getByTenantIdAndClientId({
          tenantId,
          clientId,
        });
        isEvicted = true;
        if (!occupancy) {
          log.info(`[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], No Occupancy Found In Either Occupancies or MoveOut`);

          return res.status(400).json({
            msg: CONSTANTS.MSG.INVALID_REQUEST,
            isSuccess: false,
          })
        }
      }
    }


    let collection = 0;
    let advance = 0;
    if (occupancy.status == CONSTANTS.OCCUPANCY_STATUS.MOVING_OUT || !occupancy || isEvicted) {
      const { totalCollection, advancePaid } =
        await ledgerDB.getTotalByTenantIdForMovingOut({
          tenantId,
          clientId,
        });
      collection = totalCollection;
      advance = advancePaid;
    } else {
      const { totalCollection, advancePaid } =
        await ledgerDB.getTotalByTenantId({
          tenantId,
          clientId,
        });
      collection = totalCollection;
      advance = advancePaid;
    }

    collection = collection || 0;
    advance = advance || 0;
    let total = 0;
    if (advance < 0 && collection >= 0) {
      total = Number(collection) + Number(advance);
    } else if (advance < 0 && collection < 0) {
      total = Number(advance);
    } else {
      total = Number(collection);
    }

    let totalCollectedAmt = await transactionDB.getTotalCollectionByTenantIdAndClientId({
      tenantId,
      clientId,
    });

    let totalSecurityReceived = await ledgerDB.getSecurityTransactionAmountX({
      tenantId,
      type: CONSTANTS.DUES_TYPES.SECURITY,
      roomId: occupancy.roomId,
      propId: occupancy.propId,
    });

    // let totalAdjustedFromSecurity = await ledgerDB.getUsedSecurityAmtByTenantIdAndClientId({
    //   clientId,
    //   tenantId,
    //   createdAt: moment("1976-02-18").format("YYYY-MM-DD HH:mm:ss"),
    // });
    let totalAdjustedFromSecurity = await ledgerDB.getAdjustedSecurityAmtByTenantIdAndClientId({
      clientId,
      tenantId,
    });

    let refundedAmount = 0;

    let refundedEntry = await ledgerDB.getLastRefundEntry({
      clientId,
      tenantId,
      moveInDate: occupancy.moveInDate,
    })

    if (refundedEntry) {
      const match = refundedEntry.description.match(/₹\s*(\d+)/);
      refundedAmount = match ? Number(match[1]) : 0;
    }

    let timelineLedger = [];
    /* Time based ledger logic */
    if (ledger) {
      ledger.forEach((entry: any) => {
        entry.eventDate =
          entry.amount > 0
            ? entry.createdAt
            : entry.collectionDate || entry.createdAt;
        entry.refundAmount = 0;
        if(entry.description) {
          const match = entry.description.match(/₹\s*(\d+)/);
          entry.refundAmount = match ? Number(match[1]) : 0;
        }
      });

      // ledger.sort(
      //   (a: any, b: any) =>
      //     new Date(a.eventDate).getTime() -
      //     new Date(b.eventDate).getTime()
      // );

      const balanceMap = new Map();
      const hadPartialMap = new Map();

      timelineLedger = ledger.map((entry: any) => {
        const refId = entry.referenceId || `NO_REF_${entry.id}`;

        const previousBalance = balanceMap.get(refId) || 0;
        const currentBalance = previousBalance + entry.amount;

        balanceMap.set(refId, currentBalance);

        let eventType = "UNKNOWN";
        let eventStatus = "--";

        if (entry.amount > 0) {
          // Due created
          eventType = "DUE_CREATED";
          eventStatus = "PENDING";
        } else if (entry.subType === CONSTANTS.LEDGER_SUBTYPES.MARKED_FROM_SECURITY) {
          eventType = "PAYMENT";
          eventStatus = "SECURITY_ADJUSTMENT";
        } else if (entry.subType === CONSTANTS.LEDGER_SUBTYPES.REFUND) {
          eventType = "PAYMENT";
          eventStatus = "REFUND";
        } else {
          // Payment
          eventType = "PAYMENT";

          if (currentBalance === 0 && hadPartialMap.get(refId)) {
            eventStatus = "PENDING_CLEARED";
          } else if (currentBalance === 0) {
            eventStatus = "CLEARED";
          } else if (currentBalance > 0) {
            eventStatus = "PARTIAL";
            hadPartialMap.set(refId, true);
          } else {
            eventStatus = "EXCESS";
          }
        }

        return {
          ...entry,
          referenceId: refId,
          eventType,
          eventStatus,
          balanceAfter: currentBalance,
          eventDate: entry.eventDate,
          refundAmount: entry.refundAmount,
        };
      });

      ledger.sort(
        (a: any, b: any) =>
          new Date(a.eventDate).getTime() -
          new Date(b.eventDate).getTime()
      );
    }

    log.info(
      `[${C}], [${F}], Client Id [${clientId}], Total Balance [${total}], Total Amount Collected [${totalCollectedAmt}], Advance Paid [${advance}], Security Used To Mark Dues [${totalAdjustedFromSecurity}], Refunded Amount [${refundedAmount}], Ledger sent successfully`
    );

    // log.info(`Ledgers [${JSON.stringify(ledger)}]`);

    return res.status(200).json({
      msg: "Ledger sent successfully",
      data: {
        ledger: ledger || [],
        timelineLedger: timelineLedger || [],
        totalCollection: total || 0,
        totalDues: total || 0,
        totalReceived: totalCollectedAmt || 0,
        totalAdjustedFromSecurity: totalAdjustedFromSecurity || 0,
        totalSecurityReceived: Math.abs(totalSecurityReceived.amount) || 0,
        refundedAmount: refundedAmount || 0,
        advancePaid: advance || 0,
      },
      isSuccess: true,
    });
  } catch (error: any) {
    log.info(`[${C}], [${F}], Error: ${error?.message || error}`);
    return res.status(500).json({
      msg: CONSTANTS.MSG.ERROR_MESSAGE,
      isSuccess: false,
    });
  }
};

ledger.DownloadTenantLedger = async (req: CustomRequest, res: Response) => {
  const C = "Ledger Controller";
  const F = "DownloadTenantLedger";


  try {
    const { tenantId } = req.params;
    const { e = 0 } = req.query;
    let isEvicted = e === "1";

    const userType = req.userType;

    let clientId = req.id;
    if (userType === CONSTANTS.USER_TYPE.STAFF) {
      const staff = await staffDB.getById({ id: req.id });
      if (!staff) {
        log.info(`[${C}], [${F}], Staff Id [${req.id}], No Staff Found`);
        return res
          .status(400)
          .json({ msg: CONSTANTS.MSG.INVALID_REQUEST, isSuccess: false });
      }

      clientId = staff.clientId;

      log.info(
        `[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Is Evicted [${isEvicted}], Staff Id [${req.id}], Staff Requested.....`
      );
    } else {
      log.info(
        `[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Is Evicted [${isEvicted}], Client Requested....`
      );
    }

    const tenant = await tenantDB.getById({ id: tenantId });
    if (!tenant) {
      log.info(`[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Is Evicted [${isEvicted}], No Tenant Found`);
      return res
        .status(400)
        .json({ msg: CONSTANTS.MSG.INVALID_REQUEST, isSuccess: false });
    }

    let occupancy = await occupancyDB.getByTenantIdAndClientId({
      clientId: clientId,
      tenantId: tenantId,
    });

    if (isEvicted) {
      occupancy = await moveOutDB.getByTenantIdAndClientId({
        tenantId,
        clientId,
      });
    }

    if (!occupancy) {
      log.info(`[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Is Evicted [${isEvicted}], No Occupancy Found`);
      return res.status(400).json({
        msg: CONSTANTS.MSG.INVALID_REQUEST,
        isSuccess: false,
      });
    }

    let ledger = await ledgerDB.getTenantCompleteLedgerByClientId({
      clientId: clientId,
      tenantId: Number(tenantId),
    });

    if (!ledger || ledger.length === 0) {
      log.info(`[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Is Evicted [${isEvicted}], No Ledger Found`);
      return res.status(400).json({
        msg: "No ledger entries found",
        isSuccess: false,
      });
    }
    //let output = await formatLedgerData(ledger);
    const room = await roomDB.getById({ id: occupancy.roomId });

    const property = await propertyDB.getById({ id: occupancy.propId });

    if (!property) {
      log.info(`[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Is Evicted [${isEvicted}], No Property Found`);
      return res.status(400).json({
        msg: CONSTANTS.MSG.INVALID_REQUEST,
        isSuccess: false,
      });
    }


    let templatePath = `${process.env.UPLOAD_PATH}/documents/defaults/tenant_ledger.html`;
    //let templatePath = process.env.TENANT_LEDGER_DOWNLOAD!;
    let { data: html } = await axios.get(templatePath);

    const folderName = `tenant_${occupancy.tenantId}`;

    const folderPath = `uploads/documents/client_${occupancy.clientId}/prop_${occupancy.propId}/room_${occupancy.roomId}_bed_${occupancy.bedId}/${folderName}`;

    if (!fs.existsSync(folderPath)) {
      await fsPromises.mkdir(folderPath, { recursive: true });
    }

    const urlBasePath = `${process.env.UPLOAD_PATH}/documents/client_${occupancy.clientId}/prop_${occupancy.propId}/room_${occupancy.roomId}_bed_${occupancy.bedId}/${folderName}`;

    if (!html) {
      log.info(
        `[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Client Id [${occupancy.clientId}], Prop Id [${property.id}] Template found without content`
      );
      return res
        .status(400)
        .json({ msg: CONSTANTS.MSG.ERROR_MESSAGE, isSuccess: false });
    }
    html = html.toString();

    let logo = process.env.RS_DEFAULT_LOGO_URI;

    let flatName = "";
    let fieldValue = "Room No.";
    if (property.type === CONSTANTS.PROPERTY_TYPE.FLAT) {
      const { name } = await flatDB.getById({ id: occupancy.flatId });
      flatName = name;
      fieldValue = "Flat No.";
    } else {
      flatName =
        occupancy.floor === "G" ? "Ground Floor" : "Floor " + occupancy.floor;
    }
    flatName += ` (${room.roomNum})`;
    html = html.replace(/{{logo}}/g, logo);
    html = html.replace(/{{propertyName}}/g, property.name);
    html = html.replace(/{{propertyAddress}}/g, property.address);

    html = html.replace(/{{tenantName}}/g, tenant.name);
    html = html.replace(/{{roomNo}}/g, flatName);
    html = html.replace(/{{rentalCycle}}/g, occupancy?.rentalCycle);
    html = html.replace(/{{moveInDate}}/g, occupancy?.moveInDate);
    if (isEvicted) {
      html = html.replace(/{{moveOutDate}}/g, `<p style="margin: 2px 0;"><strong>Move-out Date:</strong> ${occupancy?.moveOutDate}</p>`);
    } else {
      if(occupancy?.status === CONSTANTS.OCCUPANCY_STATUS.MOVING_OUT) {
        html = html.replace(/{{moveOutDate}}/g, `<p style="margin: 2px 0;"><strong>Moving-out Date:</strong> ${occupancy?.moveOutDate}</p>`);
      } else {
        html = html.replace(/{{moveOutDate}}/g, "");
      }
    }

    if (2 === occupancy.stayType) {
      html = html.replace(/{{stayDuration}}/g, `<strong>Stay Duration:</strong> ${occupancy?.moveInDate} - ${occupancy?.moveOutDate}`);
      html = html.replace(/{{tenantRent}}/g, `${occupancy?.rent} / Night`);
    } else {
      const agreementEndDate = moment(occupancy?.agreementStartDate).add(occupancy?.agreementPeriod, "months").subtract(1, "day").format("YYYY-MM-DD");
      html = html.replace(/{{stayDuration}}/g, `<strong>Agreement Period:</strong> ${occupancy?.moveInDate} - ${agreementEndDate}`);

      if (1 === occupancy.rentalType)
        html = html.replace(/{{tenantRent}}/g, `${occupancy?.rent} / Month`);
      else if (3 === occupancy.rentalType)
        html = html.replace(/{{tenantRent}}/g, `${occupancy?.rent} / Quarter`);
      else if (6 === occupancy.rentalType)
        html = html.replace(/{{tenantRent}}/g, `${occupancy?.rent} / Half Year`);
      else
        html = html.replace(/{{tenantRent}}/g, `${occupancy?.rent} / Year`);
    }

    const now = moment();
    const generatedString = `Generated on ${now.format('DD MMM YYYY HH:mm')}`;
    html = html.replace(/{{generatedAt}}/g, generatedString);
    /*
     * Tenant overall data
     */
  let tenantDues = await ledgerDB.getTenantTotalDueAmount({
      clientId: clientId,
      tenantId: Number(tenantId),
    });
  let tenantPaidSecurity = await ledgerDB.getLatestSecurityPaid({
      clientId: clientId,
      tenantId: Number(tenantId),
    });
  if (isEvicted) {
    tenantDues.amount = Number(tenantDues?.amount) - Number(occupancy?.security) + Math.abs(tenantPaidSecurity?.amount ? tenantPaidSecurity?.amount : 0);
  }

    let totalAdjustedFromSecurity = await ledgerDB.getAdjustedSecurityAmtByTenantIdAndClientId({
      clientId,
      tenantId,
    });
    let secAdjusted = totalAdjustedFromSecurity || 0;

    html = html.replace(/{{tenantDues}}/g, tenantDues?.amount ? tenantDues?.amount : 0);

    //log.info(`[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Tenant Dues [${JSON.stringify(tenantDues)}]`);

    let ledgerTenantCollections = await ledgerDB.getTenantTotalCollections({
      clientId: clientId,
      tenantId: Number(tenantId),
    });

    let ledgerCollection  =  Math.abs(ledgerTenantCollections?.amount ? ledgerTenantCollections?.amount : 0);
    let tenantCollections = await transactionDB.getTotalCollectionByTenantIdAndClientId({
      tenantId,
      clientId,
    });

    let collection = tenantCollections || 0;
    html = html.replace(/{{tenantCollection}}/g, collection);
    html = html.replace(/{{secAdjusted}}/g, secAdjusted);

    // let tenantPaidSecurity = await ledgerDB.getLatestSecurityPaid({
    //   clientId: clientId,
    //   tenantId: Number(tenantId),
    // });

    let paidSecurity = Math.abs(tenantPaidSecurity?.amount ? tenantPaidSecurity?.amount : 0) - Number(secAdjusted);

    html = html.replace(/{{tenantSecurityCollection}}/g, paidSecurity);

    let tenantSecurityDue = await ledgerDB.getTenantSecurityDue({
      clientId: clientId,
      tenantId: Number(tenantId)
    });

    html = html.replace(/{{tenantSecurityDue}}/g, tenantSecurityDue?.amount ? tenantSecurityDue?.amount : 0);

    let tenantDiscount = await ledgerDB.getTenantTotalDiscount({
      clientId: clientId,
      tenantId: Number(tenantId)
    });

    html = html.replace(/{{tenantDiscount}}/g, tenantDiscount?.amount ? tenantDiscount?.amount : 0);

    let netbalance = Number(tenantDues?.amount ? tenantDues?.amount : 0) - Number(ledgerCollection);

    html = html.replace(/{{netBalance}}/g, netbalance);



    let ledgerOutput = await formatLedgerData(ledger);

    log.info(`[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Formatted Ledger Data [${JSON.stringify(ledgerOutput)}]`);
    let tableRows = "";
    ledgerOutput.forEach((monthLedger, i) => {
      let excessBalance = "";
      // if(i === 0 ){
      //   if(monthLedger.rows[0].balance < 0)
      //     excessBalance = `(Excess Balance: <strong
      //                         style="Color: #28a745;font-weight: bold;">${monthLedger.rows[0].balance < 0 ? monthLedger.rows[0].balance : 0}</strong>)` 


      // }
      if (monthLedger.month) {
        tableRows += `<tr>
                    <td colspan="5"><Span style="    display: inline-block;width: 50%;"><STRONG>${monthLedger.month}</STRONG></span><Span
                            style="display: inline-block;width: 50%;text-align: right;">${excessBalance}</Span></td>
                </tr>`;
      }
      monthLedger.rows.forEach((row, j) => {
        if (row.payments < 0) {
          let utrNo = "";
          let bankRefNum = "";
          let remark = "";
          let recordedBy = "";
          let mode = "";
          if(row.mode != '') {
            mode = `<BR><span style="font-size:9px;color: #888891"><b>Mode:</b> ${row.mode}</span>`;
          }
          if(row.utr != '') {
            utrNo = `<BR><span style="font-size:9px;color: #888891"><b>Utr No.:</b> ${row.utr}</span>`;
          }
          if(row.bankRefNum != '') {
            bankRefNum = `<BR><span style="font-size:9px;color: #888891"><b>Bank Ref:</b> ${row.bankRefNum}</span>`;
          }
          if(row.recordedBy != '') {
            recordedBy = `<BR><span style="font-size:9px;color: #888891"><b>Recorded By:</b> ${row.recordedBy}</span>`;
          }
          if(row.remark != '') {
            remark = `<BR><span style="font-size:9px;color: #888891"><b>Remarks:</b> ${row.remark}</span>`;
          }
          
          tableRows += `<tr>
                    <td><span style="font-size:10px;">${row.date}</span></td>
                    <td><span style="font-size:10px;">${row.description}</span>${mode}${utrNo}${bankRefNum}${recordedBy}${remark}</td>
                    <td></td>
                    <td style="background-color:#dcfce7;font-size:10px;">${Math.abs(row.payments)}</td>
                    <td></td>
                </tr>`;
        } else
          tableRows += `<tr>
                    <td style= "font-size:10px;">${row.date}</td>
                    <td style= "font-size:10px;">${row.description}</td>
                    <td style="background-color:#ffe2e2;font-size:10px;">${row.dues}</td>
                    <td></td>
                    <td style= "font-size:10px;">${row.dues}</td>
                </tr>`;
      })
      tableRows += ` <tr>
                    <td colspan="2" style="text-align:center"><STRONG> ${monthLedger.month.split(" ")[0]} Total</STRONG></td>
                    <td><STRONG>${monthLedger.totalDues}</STRONG></td>
                    <td><STRONG>${Math.abs(monthLedger.totalPayments)}</STRONG></td>
                    <td><STRONG>${monthLedger.totalDues + monthLedger.totalPayments}</STRONG></td>
                </tr>
`;
    })
    html = html.replace(/{{tableRows}}/g, tableRows);
    html = html.replace(/\n/g, "");

    const options = {
      format: "A4",
      orientation: "portrait",
      border: "10mm",
      childProcessOptions: {
        env: {
          OPENSSL_CONF: "/dev/null",
        },
      },
    };

    const filename = `tenantLedger_${tenantId}.pdf`;
    const url = `${urlBasePath}/${filename}`;

    var document = {
      html: html,
      path: `${folderPath}/${filename}`,
      data: {},
      type: "",
    };

    await pdf.create(document, options);

    log.info(
      `[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Is Evicted [${isEvicted}], URL [${url}]`
    );
    log.info(
      `[${C}], [${F}], Client Id [${clientId}], Tenant Id [${tenantId}], Is Evicted [${isEvicted}], Tenant profile document created Successfully`
    );
    return res.status(200).json({
      msg: "Tenant ledger document created Successfully",
      link: url,
      isSuccess: true,
    });
  } catch (error: any) {
    log.info(`[${C}], [${F}], Error: ${error?.message || error}`);

    return res.status(500).json({
      msg: CONSTANTS.MSG.ERROR_MESSAGE,
      isSuccess: false,
    });
  }
};

export default ledger;
