import axios from "axios";
import AppError from "../../errors/AppError";
import endPointQuery from "../../helpers/EndPointQuery";
import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
import { getWbot } from "../../libs/wbot";

const CheckIsValidContact = async (
  number: string,
  ignoreThrow?: boolean
): Promise<any> => {
  const defaultWhatsapp = await GetDefaultWhatsApp({
    ignoreNoWhatsappFound: true
  });

  let isValidNumber;

  if (defaultWhatsapp) {
    const wbot_url = await getWbot(defaultWhatsapp.id);

    let { data } = await endPointQuery(`${wbot_url}/api/validate`, {
      mobile: `${number}`
    });

    if (data?.isValid) {
      isValidNumber = data;
    }
  }

  try {
    let _status: any;

    if (!isValidNumber) { 

      const { data, status } = await axios.post(
        `${process.env.WHATS_NUMBER_VALIDATOR_URL}/api/validate`,
        { mobile: number },
        {
          headers: {
            "Content-Type": "application/json"
          }
        }
      );

      isValidNumber = data;
      _status = status; 
    }
    if (ignoreThrow) return isValidNumber?.number;
   
  console.log('_status: ', _status)

    if (_status && _status == 422) throw new AppError("ERR_NO_WAPP_FOUND");

    if (!isValidNumber || (isValidNumber && !isValidNumber.isValid)) {
      throw new AppError("invalidNumber");
    }

    if (isValidNumber && isValidNumber?.isValid) return isValidNumber.number;
  } catch (err: any) {
    if (err.message === "invalidNumber") {
      throw new AppError("ERR_WAPP_INVALID_CONTACT");
    }

    throw new AppError("ERR_WAPP_CHECK_CONTACT");
  }
};

export default CheckIsValidContact;
