import path from "path";
import propertyDB from "../models/property.model";
import CONSTANTS from "../config/constants";
import fs from "fs";
import log from "../config/log";

export const copyRentAgreement = async ({
  clientId,
  propId,
}: {
  clientId: number;
  propId: number;
}) => {
  const U = "Copy Rent Agreement";
  const F = "copyRentAgreement";
  try {
    // const BASE_UPLOADS_DIR = "/var/www/html/PROJECTS/Kipinn/cms/backend/uploads";
    const BASE_UPLOADS_DIR = process.env.BASE_UPLOADS_CMS!;
    const SIGNATURES_BASE = path.join(BASE_UPLOADS_DIR, "owner_signatures");
    const AGREEMENTS_BASE = path.join(BASE_UPLOADS_DIR, "rent_agreements");

    let sourceSignaturePropId = null;
    let sourceAgreementPropId = null;

    // const activeProperties = await propertyDB.getPropIdsByClientId({
    //   clientId,
    //   status: CONSTANTS.PROPERTY_STATUS.ACTIVE,
    // });
    let activeRA = await propertyDB.getLastRentAgreementForActiveProp({ clientId });
    if (activeRA) {
      sourceSignaturePropId = activeRA.propId;
      sourceAgreementPropId = activeRA.propId;

      // if (activeProperties && activeProperties.length > 0) {
      //   for (let activeProperty of activeProperties) {
      //     const sigPath = path.join(SIGNATURES_BASE, String(activeProperty.id));
      //     const agreementPath = path.join(
      //       AGREEMENTS_BASE,
      //       String(activeProperty.id),
      //     );
      //     if (fs.existsSync(sigPath) && fs.existsSync(agreementPath)) {
      //       sourceSignaturePropId = activeProperty.id;
      //       sourceAgreementPropId = activeProperty.id;
      //       break;
      //     }
      //   }
      // }

      log.info(
        `[${U}], [${F}], Client Id [${clientId}], Signature Source Prop Id [${sourceSignaturePropId}], Signature Dest Prop Id [${propId}], Agreement Source Prop Id [${sourceAgreementPropId}], Agreement Dest Prop Id [${propId}]`,
      );

      const copyFolderRecursive = (srcDir: any, targetDir: any) => {
        if (!fs.existsSync(srcDir)) return;
        fs.mkdirSync(targetDir, { recursive: true });

        fs.cpSync(srcDir, targetDir, { recursive: true });
      };

      if (sourceSignaturePropId) {
        const signatureSrc = path.join(
          SIGNATURES_BASE,
          String(sourceSignaturePropId),
        );
        const signatureDest = path.join(SIGNATURES_BASE, String(propId));

        log.info(
        `[${U}], [${F}], Client Id [${clientId}], Signature SRC [${signatureSrc}], DEST [${signatureDest}]`,
        );
        copyFolderRecursive(signatureSrc, signatureDest);
      }

      if (sourceAgreementPropId) {
        const agreementSrc = path.join(
          AGREEMENTS_BASE,
          String(sourceAgreementPropId),
        );
        const agreementDest = path.join(AGREEMENTS_BASE, String(propId));
        log.info(
        `[${U}], [${F}], Client Id [${clientId}], Agreement SRC [${agreementSrc}], DEST [${agreementDest}]`,
        );
        copyFolderRecursive(agreementSrc, agreementDest);
      }
      let pathUrl = activeRA?.path.replace(activeRA.propId, String(propId));
        let signaturePathUrl = activeRA?.signaturePath.replace(activeRA.propId, String(propId));
        await propertyDB.addRentAgreement({
          clientId,
          propId,
          path: pathUrl,
          signaturePath: signaturePathUrl,
        });
        propertyDB.enableRentAgreement({
          id: propId,
        })
        
    } else {
      log.info(
        `[${U}], [${F}], Client Id [${clientId}], Signature Source Prop Id [${sourceSignaturePropId}], No agreement is active as of now`,
      );
    }
  } catch (error: any) {
    log.info(`[${U}], [${F}], Error: ${error?.message || error}`);
  }
};
