"use strict";

const hubspot = require("@hubspot/api-client");
const config = require("../config");

const HB_PERFIL = {
  free: "Otros",
  guest: "Invitado",
  tutor: "Profesor",
  student: "Estudiante",
};

function _getMemberByEmail(userEmail) {
  // Configure API key authorization: api-key
  const defaultClient = new hubspot.Client({ accessToken: config.hubspot.API_KEY });

  return new Promise(function (resolve, reject) {
    defaultClient.crm.contacts.searchApi
      .doSearch({
        filterGroups: [
          {
            filters: [
              {
                propertyName: "email",
                operator: "EQ",
                value: userEmail,
              },
            ],
          },
        ],
        properties: [
          "email",
          "firstname",
          "lastname",
          "phone",
          "perfil",
          "entidad_protagonista",
          "ciudad_del_evento",
          "pais",
          "ano_del_congreso",
          "tipo_de_evento",
        ],
      })
      .then(function (data) {
        /**
         * {
            total: 1,
            results: [
              {
                createdAt: "2023-07-25T08:19:05.729Z",
                archived: false,
                id: "16173",
                properties: {
                  createdate: "2023-07-25T08:19:05.729Z",
                  email: "darranz@rodax-software.com",
                  hs_object_id: "16173",
                  lastmodifieddate: "2024-04-17T00:46:35.476Z",
                },
                updatedAt: "2024-04-17T00:46:35.476Z",
              },
            ],
          }
         */
        if (data.total === 1) {
          resolve(data.results[0]);
        } else {
          resolve(null);
        }
      })
      .catch(function (error) {
        console.error(error);
        reject(error);
      });
  });
}

function _createMember(member) {
  // Configure API key authorization: api-key
  const defaultClient = new hubspot.Client({ accessToken: config.hubspot.API_KEY });

  return new Promise(function (resolve, reject) {
    /**
     * member = {
        id: "3cc58b92-d144-492d-a8e8-9e1294b5b10b",
        source: "app",
        event_name: "Sevilla 2023 - 22ª Edición",
        event_date: "2024-06-03T07:00:00.000Z",
        event_marketing_list: null,
        date_inscription: "2024-05-29T13:52:01.752Z",
        code_ticket: "ENT-99919197",
        validated: true,
        reservation_code: null,
        color: "darkgreen",
        description: "ENTRADA",
        qrConfig: null,
        qrCode: null,
        email: "darranz@rodax-software.com",
        name: "David",
        surname: "Arranz Puerta",
        phone: "+34629905522",
        profile: "tutor",
        userId: "e52294c5-e8c3-45b1-97ea-6e0a6c36eefa",
        entity: "Asoc Nena Paine",
      }
     */

    const newContact = {
      email: member.email,
      firstname: member.name,
      lastname: member.surname,
      phone: member.phone,
      perfil: HB_PERFIL[member.profile] || HB_PERFIL.free,
      entidad_protagonista: member.entity ? member.entity : "",
    };

    defaultClient.crm.contacts.basicApi
      .create({
        properties: newContact,
      })
      .then(function (newContact) {
        resolve(newContact);
      })
      .catch(function (error) {
        console.error(error);
        reject(error);
      });
  });
}

function _updateMember(email, member) {
  // Configure API key authorization: api-key
  const defaultClient = new hubspot.Client({ accessToken: config.hubspot.API_KEY });

  return new Promise(function (resolve, reject) {
    /**
     * member = {
        email: "darranz@rodax-software.com",
        name: "David",
        surname: "Arranz Puerta",
        userId: "e52294c5-e8c3-45b1-97ea-6e0a6c36eefa",
        profile: "tutor",
        entity: "Asoc Nena Paine",
      }     
    */

    _getMemberByEmail(email).then((data) => {
      if (data && data.id) {
        defaultClient.crm.contacts.basicApi
          .update(data.id, {
            properties: {
              email: member.email,
              firstname: member.name,
              lastname: member.surname,
              phone: member.phone,
              perfil: HB_PERFIL[member.profile] || HB_PERFIL.free,
              entidad_protagonista: member.entity ? member.entity : "",
            },
          })
          .then(function (updatedContact) {
            /**
             * response = {
                createdAt: "2023-07-25T08:19:05.729Z",
                archived: false,
                id: "16173",
                properties: {
                  ano_del_congreso: "2023",
                  ciudad_del_evento: "Barcelona",
                  createdate: "2023-07-25T08:19:05.729Z",
                  email: "darranz@rodax-software.com",
                  entidad_protagonista: "",
                  firstname: "David",
                  hs_object_id: "16173",
                  lastmodifieddate: "2024-05-29T09:43:07.118Z",
                  lastname: "Arranz Puerta",
                  pais: null,
                  perfil: "Otros;Profesor;Estudiante",
                  phone: "+34629905522",
                  tipo_de_evento: "Congreso",
                },
                updatedAt: "2024-05-29T09:43:07.118Z",
              }}
             */

            resolve(updatedContact);
          })
          .catch(function (error) {
            console.error(error);
            reject(error);
          });
      }
    });
  });
}

function _deleteMember(email) {
  // Configure API key authorization: api-key
  const defaultClient = new hubspot.Client({ accessToken: config.hubspot.API_KEY });

  return new Promise(function (resolve, reject) {
    _getMemberByEmail(email).then((data) => {
      if (data && data.id) {
        defaultClient.crm.contacts.basicApi
          .archive(data.id)
          .then(function (response) {
            resolve();
          })
          .catch(function (error) {
            console.error(error);
            reject(error);
          });
      }
    });
  });
}

async function _addInscriptionToMember(hbContact, member) {
  /**
   * {
      id: "700d5edd-c8da-4179-adfb-d41abeed1441",
      source: "app",
      event_name: "Sevilla 2023 - 22ª Edición",
      event_date: "2024-06-03T07:00:00.000Z",
      event_marketing_list: null,
      event_country: "España",
      event_city: "Sevilla",
      date_inscription: "2024-05-30T15:01:31.420Z",
      code_ticket: "ENT-09488890",
      validated: true,
      reservation_code: null,
      color: "darkgreen",
      description: "ENTRADA",
      qrConfig: null,
      qrCode: null,
      email: "darranz@rodax-software.com",
      name: "david",
      surname: "arranz",
      phone: "+34629905522",
      profile: "free",
      userId: "e52294c5-e8c3-45b1-97ea-6e0a6c36eefa",
      entity: null,
    }
   */

  const { properties } = hbContact;
  let ciudad_del_evento, pais, ano_del_congreso;

  if (member.event_city) {
    ciudad_del_evento = String(properties.ciudad_del_evento || "").split(";");

    let event_city = member.event_city;

    // caso especial para Toluca Youth / Teen
    if (String(member.event_name).includes("Teen")) {
      event_city = `${event_city} Teen`;
    }

    if (String(member.event_name).includes("Youth")) {
      event_city = `${event_city} Youth`;
    }
    // fin de caso especial

    ciudad_del_evento.push(event_city);
    ciudad_del_evento = ciudad_del_evento.join(";");
  }

  if (member.event_country) {
    pais = String(properties.pais || "").split(";");
    pais.push(member.event_country);
    pais = pais.join(";");
  }

  if (member.event_date) {
    ano_del_congreso = String(properties.ano_del_congreso || "").split(";");
    ano_del_congreso.push(String(new Date(member.event_date).getUTCFullYear()));
    ano_del_congreso = ano_del_congreso.join(";");
  }

  const defaultClient = new hubspot.Client({ accessToken: config.hubspot.API_KEY });
  const updatedContact = await defaultClient.crm.contacts.basicApi.update(hbContact.id, {
    properties: {
      ciudad_del_evento,
      pais,
      ano_del_congreso,
      tipo_de_evento: "Congreso",
    },
  });

  return updatedContact;
}

async function _deleteInscriptionFromMember(hbContact, inscription) {
  let {
    event: {
      name: event_name,
      init_date,
      location: { city: delete_city, country: delete_country },
    },
  } = inscription;

  const { properties } = hbContact;

  // caso especial para Toluca Youth / Teen
  if (String(event_name).includes("Teen")) {
    delete_city = `${delete_city} Teen`;
  }

  if (String(event_name).includes("Youth")) {
    delete_city = `${delete_city} Youth`;
  }
  // fin de caso especial

  let ciudad_del_evento = String(properties.ciudad_del_evento || "").split(";");
  if (ciudad_del_evento.includes(delete_city)) {
    ciudad_del_evento = ciudad_del_evento.filter((ciudad) => ciudad !== delete_city);
  }

  const delete_year = String(new Date(init_date).getUTCFullYear());
  let ano_del_congreso = String(properties.ano_del_congreso || "").split(";");
  if (ano_del_congreso.includes(delete_year)) {
    if (ano_del_congreso.length > 1 || ciudad_del_evento.length === 0) {
      ano_del_congreso = ano_del_congreso.filter((year) => year !== delete_year);
    }
  }

  let pais = String(properties.pais || "").split(";");
  if (pais.includes(delete_country)) {
    if (pais.length > 1 || ciudad_del_evento.length === 0) {
      pais = pais.filter((item) => item !== delete_country);
    }
  }

  const defaultClient = new hubspot.Client({ accessToken: config.hubspot.API_KEY });
  const updatedContact = await defaultClient.crm.contacts.basicApi.update(hbContact.id, {
    properties: {
      ciudad_del_evento: ciudad_del_evento.join(";"),
      pais: pais.join(";"),
      ano_del_congreso: ano_del_congreso.join(";"),
    },
  });

  return updatedContact;
}

/***************************************************************************** */

async function addMemberToList(listId, member) {
  let hbContact = await _getMemberByEmail(member.email);
  if (hbContact && hbContact.id) {
    hbContact = await _addInscriptionToMember(hbContact, member);
  } else {
    hbContact = await _createMember(member);
    await _addInscriptionToMember(hbContact, member);
  }
  return hbContact;
}

function updateMemberByEmail(userEmail, userData) {
  return _updateMember(userEmail, userData);
}

async function deleteMemberFromList(listId, userEmail, inscription) {
  // <-- viene por eliminar inscripción

  let hbContact = await _getMemberByEmail(userEmail);
  if (hbContact && hbContact.id) {
    await _deleteInscriptionFromMember(hbContact, inscription);
  }
  return;
}

function deleteMemberByEmail(userEmail) {
  // <- viene por borrar usuario
  return _deleteMember(userEmail);
}

function getMemberByEmail(userEmail) {
  return _getMemberByEmail(userEmail).then((data) => data !== null);
}

module.exports = {
  addMemberToList,
  deleteMemberFromList,
  updateMemberByEmail,
  deleteMemberByEmail,
  getMemberByEmail,
};
