import moment from "moment";
import log from "../config/log";
import eqaroPropertiesDB from "../models/eqaroProperties.model";
import eqaroTenantsDB from "../models/eqaroTenants.model";
import occupancyDB from "../models/occupancy.model";
import eqaroAPIs from "./eqaroAPIs";
import CONSTANTS from "../config/constants";

export const completeEqaroPayment = async ({
  tenantId,
  bondAmount
  }: {tenantId:any; bondAmount:number}) => {
    const C = "Eqaro Controller";
    const F = "TenantEmailOTPVerify";
    const U = "completeEqaroPayment";
    log.info(
        `[${C}], [${F}], [${U}], Tenant Id [${tenantId}], Bond Amount [${bondAmount}] Initiating Bond Payment`
      );

    let data = null;

    let eqaroTenant = await eqaroTenantsDB.getByTenantId({ tenantId });
    if (!eqaroTenant) {
      log.info(
        `[${C}], [${F}], [${U}], TenantId [${tenantId}] No tenant found with given id`
      );
      return {
        msg: "Invalid tenant id",
        isSuccess: false,
      };
    }

    const occupancy = await occupancyDB.getByTenantId({ tenantId });
    if (!occupancy) {
      log.info(
        `[${C}], [${F}], [${U}], TenantId [${tenantId}] No occupancy found with given id`
      );
      return {
        msg: "No occupancy found for given tenant",
        isSuccess: false,
      };
    }

    const eqaroProperty = await eqaroPropertiesDB.getByPropId({
      propId: occupancy.propId,
    });

    if (!eqaroProperty) {
      log.info(`[${C}], [${F}], [${U}], Tenant Id [${tenantId}], Prop Id [${occupancy.propId}], Property not found in eqaro properties`);
      return {
        msg: "Property not found",
        isSuccess: false,
      };
    }

    log.info(`[${C}], [${F}], [${U}], Tenant Id [${tenantId}], propId [${eqaroProperty.propId}], Rent [${occupancy.rent}], Bond Amount [${occupancy.rent * eqaroProperty.bondAmountMul}], Property Id [${eqaroProperty.propertyId}]`);
    let effectiveBondAmount = occupancy.rent * eqaroProperty.bondAmountMul;
    const initiateBondBody = {
      tenantId: eqaroTenant.eqaroUserId,
      propertyId: eqaroProperty.propertyId,
      bondAmount: effectiveBondAmount,
      type: "buy_bond",
      bondEffectiveDate: moment().format('YYYY-MM-DD'),
    };

    const { isSuccess, response } = await eqaroAPIs.paymentPostApi(
      eqaroTenant.mobile,
      eqaroTenant.accessToken,
      "paymentGateway/initiate",
      initiateBondBody
    );
    if (isSuccess && response.data.eqaroOrderId) {
      log.info(
        `[${C}], [${F}], [${U}], Tenant Id [${tenantId}], Bond Effective Date [${occupancy.moveInDate}], Bond OrderId [${response.data.eqaroOrderId}] Bond Payment Initiation Successfull`
      );

      await eqaroTenantsDB.updateInitiateBondParams({
        tenantId: tenantId,
        bondFee: response.data.amount,
        bondEffectiveDate: moment().format("YYYY-MM-DD"),
        orderId: response.data.eqaroOrderId,
        bondAmount: effectiveBondAmount,
      });

      eqaroTenant = await eqaroTenantsDB.getByTenantId({ tenantId });

      log.info(`[${C}], [${F}], [${U}], Tenant Id [${tenantId}], Initiating Complete Bond API...`);

      const completeBondBody = {
        tenantId: eqaroTenant.eqaroUserId,
        bondEffectiveDate: moment(eqaroTenant.bondEffectiveDate).format(
          "YYYY-MM-DD"
        ),
        eqaroOrderId: eqaroTenant.orderId,
      };
  
      const { isSuccess, response: completeBondResponse } = await eqaroAPIs.paymentPostApi(
        eqaroTenant.mobile,
        eqaroTenant.accessToken,
        "payment/complete",
        completeBondBody
      );

      if (isSuccess && completeBondResponse.data.message === "Payment Successful!!") {
        log.info(
          `[${C}], [${F}], [${U}], Tenant Id [${tenantId}], BondId [${completeBondResponse.data.bondId}], Bond Fee [${eqaroTenant.bondFee}], Bond Payment Successful`
        );
  
        await eqaroTenantsDB.updateCompleteBondParams({
          tenantId: tenantId,
          bondId: completeBondResponse.data.bondId,
          bondExpiryDate: completeBondResponse.data.expiryDate,
        });
  
        await eqaroTenantsDB.updateStatus({
          tenantId: eqaroTenant.tenantId,
          status: CONSTANTS.EQARO_TENANT_STATUS.PAYMENT_DONE,
        });

        data = {
          msg: "Bond Payment Successful",
          isSuccess: true,
        };

        return data;

      } else {
        log.info(
          `[${C}], [${F}], [${U}], Tenant Id [${tenantId}], Bond Payment Failed, No response from Eqaro`
        );

        data = {
          msg: "Bond Payment Failed, No response from Eqaro",
          isSuccess: false,
        }

        return data;
      }
    } else if (response) {
      log.info(
        `[${C}], [${F}], [${U}], Tenant Id [${tenantId}], Bond Effective Date [${occupancy.moveInDate}], Bond payment initiation failed due to internal error`
      );
      log.info(
        `[completeEqaroPayment], Tenant Id [${tenantId}], Message [${response.message}]`
      );
      if (response.message === "Bond already exist for this tenant") {

        data = {
          msg: "Bond already exist for this tenant",
          isSuccess: true,
          bondExist: true,
          status: eqaroTenant.status,
        };

        return data;
      } else if (response.message === "The Guarantee Value amount must be at least INR 7000") {

        data = {
          msg: "The Guarantee Value amount must be at least INR 7000",
          isSuccess: false,
          bondExist: false,
        };

        return data;
      } else {

        data = {
          msg: "Bond payment initiation failed due to internal error",
          isSuccess: false,
          bondExist: false,
        };

        return data;
      }
    } else {
      log.info(
        `[${C}], [${F}], [${U}], Tenant Id [${tenantId}], Bond Effective Date [${occupancy.moveInDate}], Bond payment initiation failed, no response from Eqaro`
      );

      data = {
        msg: "Bond Payment Initiation Failed, No response from Eqaro",
        isSuccess: false,
        bondExist: false,
      }

      return data;
    }
};