import { phone } from "phone";
import { GET_PHONE_NUMBER_OPT_OUTS_BY_NUMBERS } from "../graphql/phone-number-opt-out.queries";

/**
 * Check if phone numbers are opted out for a given bodyshop
 * @param {Object} apolloClient - Apollo Client instance
 * @param {string} bodyshopId - The ID of the bodyshop
 * @param {string[]} phoneNumbers - Array of phone numbers to check
 * @returns {Promise<Set<string>>} - Set of normalized opted-out phone numbers
 */
export const phoneNumberOptOutService = async (apolloClient, bodyshopId, phoneNumbers) => {
  if (!apolloClient || !bodyshopId || !phoneNumbers?.length) {
    return new Set();
  }

  // Normalize phone numbers (remove +1 for CA numbers)
  const normalizedPhones = phoneNumbers
    .filter(Boolean)
    .map((num) => phone(num, "CA").phoneNumber?.replace(/^\+1/, ""))
    .filter(Boolean);

  if (!normalizedPhones.length) {
    return new Set();
  }

  const optedOutPhones = new Set();

  try {
    const { data } = await apolloClient.query({
      query: GET_PHONE_NUMBER_OPT_OUTS_BY_NUMBERS,
      variables: {
        bodyshopid: bodyshopId,
        phone_numbers: normalizedPhones // Array of phone numbers
      },
      fetchPolicy: "network-only"
    });

    if (data?.phone_number_opt_out?.length) {
      data.phone_number_opt_out.forEach((optOut) => {
        optedOutPhones.add(optOut.phone_number);
      });
    }
  } catch (error) {
    console.error("Error checking opt-out statuses:", error);
  }

  return optedOutPhones;
};
