import { getHubspotInfo } from "../apis";
import { HubSpotContactResponse, HubSpotContactResults } from "../types";

interface HSResponse {
  id: string;
  properties: {
    company: null | string;
    createdate: string;
    cuil: string;
    email: string;
    firstname: string;
    hs_object_id: string;
    hs_whatsapp_phone_number: string;
    lastmodifieddate: string;
    lastname: string;
    mobilephone: string;
    phone: string;
  };
  createdAt: string;
  updatedAt: string;
  archived: boolean;
  url: string;
}

type HubSpotServiceResponse =
  | {
      ok: true;
      found: true;
      contact: HubSpotContactResults;
    }
  | {
      ok: true;
      found: false;
      contact: null;
    }
  | {
      ok: false;
      found: false;
      contact: null;
    };

function responseAdapter({
  data,
}: {
  data: HSResponse;
}): HubSpotContactResults {
  const { properties } = data;
  return {
    id: data.id,
    properties: {
      email: properties?.email ?? "",
      firstname: properties?.firstname ?? properties?.company ?? "",
      hs_object_id: properties.hs_object_id,
      hs_whatsapp_phone_number: properties.hs_whatsapp_phone_number ?? "",
      lastname: properties?.lastname ?? "",
      mobilephone: properties?.mobilephone ?? "",
      phone: properties?.phone ?? "",
    },
  };
}

export const getHubspotContact = async (
  cuit: string,
): Promise<HubSpotServiceResponse> => {
  try {
    const data = (await getHubspotInfo(cuit)) as HSResponse;

    const contact = responseAdapter({ data });

    return {
      ok: true,
      found: true,
      contact,
    };
  } catch {
    return {
      ok: false,
      found: false,
      contact: null,
    };
  }
};
