import CONSTANTS from "../config/constants";
import log from "../config/log";
import eqaroTenantsDB from "../models/eqaroTenants.model";
import eqaroAPIs from "./eqaroAPIs";

export const eqaroMainEligibilityCheck = async (eqaroTenant: any) => {
  const C = "Eqaro Main Eligibility Check";
  const F = "eqaroMainEligibilityCheck";
  const U = "eqaroMainEligibilityCheck";
  try {
    log.info(
      `[${C}], [${F}], Mobile [${eqaroTenant.mobile}], Performing main eligibility check`
    );

    const { isSuccess, response } = await eqaroAPIs.getApi(
      eqaroTenant.mobile,
      eqaroTenant.accessToken,
      `eligibility/check/${eqaroTenant.eqaroUserId}`
    );
    if (!isSuccess) {
      log.info(
        `[${C}], [${F}], Mobile [${eqaroTenant.mobile}], Error in main eligibility check`
      );

      return {
        msg: CONSTANTS.MSG.ERROR_MESSAGE,
        isSuccess: false,
      };
    } else if (response.data.status === "eligible") {
      log.info(
        `[${C}], [${F}], Mobile [${eqaroTenant.mobile}], Main eligibility approved`
      );

      await eqaroTenantsDB.updateStatus({
        tenantId: eqaroTenant.tenantId,
        status: CONSTANTS.EQARO_TENANT_STATUS.MAIN_ELIGIBILITY_VERIFICATION_DONE,
      });

      let status = CONSTANTS.EQARO_TENANT_STATUS.MAIN_ELIGIBILITY_VERIFICATION_DONE;

      return {
        msg: "Main eligibility approved",
        isSuccess: true,
        status: status,
        bondFee: 10000, //hard coded for now
      };
    } else if (response.data.status === "ineligible") {
      log.info(
        `[${C}], [${F}], Mobile [${eqaroTenant.mobile}], Tenant is not eligible for eqaro bond`
      );

      return {
        msg: response?.data?.elibility?.messageToShow || "We regret to inform you that we are unable to offer you Eqaros Rental Guarantee at this time. Please check back after 90 days.",
        isSuccess: false,
      };
    } else {
      log.info(
        `[${C}], [${F}], Mobile [${eqaroTenant.mobile}], Failure in main eligibility check`
      );

      return {
        msg: "Failure in main eligibility check",
        isSuccess: false,
      };
    }
  } catch (error: any) {
    log.info(
      `[Eqaro postApi], Mobile [${eqaroTenant.mobile}], Error ${
        JSON.stringify(error?.response?.data) || error?.message || error
      }`
    );

    return {
      isSuccess: false,
      response: error?.response?.data || error?.message || error,
    };
  }
};

export default eqaroMainEligibilityCheck;
