import { hubspot } from "@hubspot/ui-extensions";
import { createHubspotContact } from "./createHubspotContact";

type RequestBody = {
  firstname: string;
  lastname: string;
  cuil: string;
  phone: string;
  phoneType: string;
  email: string;
  emailType: string;
  emailStatusArca: string;
  mobilePhone: string;
  whatsapp: string;
};

type ServiceResponse =
  | {
      status: "ok";
      idLink: string;
    }
  | {
      status: "ErrorDuplicate";
      idLink: string;
    }
  | {
      status: "ErrorCreation";
      idLink: null;
    };

export const createContact = async (
  body: RequestBody,
): Promise<ServiceResponse> => {
  try {

    const response = await createHubspotContact(body);
    console.log("Response from createHubspotContact:", response);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const res = await response.json();

    // Encontré duplicado
    if (res?.contact && res.contact.category === "CONFLICT") {
      const hubspotID: string = res.contact.message.split(": ")[1];
      return {
        status: "ErrorDuplicate",
        idLink: hubspotID,
      };
    }

    if (res.status !== "ok" || !res.contact || !res.contact.url) {
      throw new Error("Respuesta del servidor incompleta o inválida");
    }
    return {
      status: "ok",
      idLink: res.contact.id as string,
    };
  } catch (error) {
    console.warn(error);
    return {
      status: "ErrorCreation",
      idLink: null,
    };
  }
};
