import type { ARCAResult, ContactInfo, HubSpotContactResults } from "../types";
import { searchLandline, searchMobile } from "./ARCAFunctions.helper";
import { getBestEmail } from "./getBestEmail.helper";

export const getContactInfo = (
  arcaInfo: ARCAResult,
  validCUIT: string,
  hsInfo: HubSpotContactResults | null,
): ContactInfo => {
  const email = getBestEmail(arcaInfo.emails);
  const firstValidValue = (...values: Array<string | null | undefined>) => {
    return values.find((value) => value && value.trim() !== "") ?? "";
  };

  if (hsInfo) {
    const landline = firstValidValue(
      searchLandline(arcaInfo).number,
      hsInfo?.properties.phone,
    );

    const mobile = firstValidValue(
      searchMobile(arcaInfo).number,
      hsInfo?.properties.mobilephone,
      hsInfo?.properties.hs_whatsapp_phone_number,
    );

    return {
      hs_id: hsInfo.id,
      name: hsInfo.properties.firstname ?? arcaInfo.nombre ?? "",
      last_name: hsInfo.properties.lastname ?? arcaInfo.apellido ?? "",
      cuit: validCUIT,
      landline,
      mobile,
      email: email.email,
      email_type: email.type,
    };
  }

  return {
    hs_id: "",
    name: arcaInfo.nombre,
    last_name: arcaInfo.apellido,
    cuit: validCUIT,
    landline: searchLandline(arcaInfo).number,
    mobile: searchMobile(arcaInfo).number,
    email: email.email,
    email_type: email.type,
  };
};
