const axios = require("axios");

exports.emailValidator = async (email) => {
  if (!email) return { isValidEmail: false };
  const options = {
    method: "GET",
    url: "https://api.usebouncer.com/v1.1/email/verify",
    params: { email },
    headers: { "x-api-key": process.env.BOUNCER_API_KEY },
  };

  try {
    let isValidEmail = true;

    const whiteListedDomains = ["buildhub.ph"];
    const receiverDomain = email.split("@")[1];

    if (whiteListedDomains.includes(receiverDomain)) {
      return { isValidEmail: true };
    }

    const response = await axios(options);
    const responseData = response.data;

    const isDeliverable = responseData.status === "deliverable" || responseData.status === "risky";

    const isDisposableEmail = responseData.domain.disposable !== "no" && responseData.domain.disposable !== "unknown";

    if (!isDeliverable) {
      isValidEmail = false;
    }
    if (isDisposableEmail) {
      isValidEmail = false;
    }

    return { isValidEmail };
  } catch (error) {
    console.error("Error verifying email:", error);
    return { isValidEmail: true };
  }
};
