import { b as getLocation } from "./CalEventParser-gVLQw-Bk.js";
import { l as logger } from "./i18n-49-r55rr.js";
import { a as appConfig } from "./utils-Nhmgt8pa.js";
class PipedriveCrmService {
  constructor(credential) {
    this.getMeetingBody = (event) => {
      return `<b>${event.organizer.language.translate("invitee_timezone")}:</b> ${event.attendees[0].timeZone}<br><br><b>${event.organizer.language.translate("share_additional_notes")}</b><br>${event.additionalNotes || "-"}`;
    };
    this.createPipedriveEvent = async (event, contacts) => {
      const eventPayload = {
        subject: event.title,
        startDateTime: event.startTime,
        endDateTime: event.endTime,
        description: this.getMeetingBody(event),
        location: getLocation(event),
        associations: {
          contactId: String(contacts[0].id)
        }
      };
      const headers = new Headers();
      headers.append("x-revert-api-token", this.revertApiKey);
      headers.append("x-revert-t-id", this.tenantId);
      headers.append("Content-Type", "application/json");
      const eventBody = JSON.stringify(eventPayload);
      const requestOptions = {
        method: "POST",
        headers,
        body: eventBody
      };
      return await fetch(`${this.revertApiUrl}crm/events`, requestOptions);
    };
    this.updateMeeting = async (uid, event) => {
      const eventPayload = {
        subject: event.title,
        startDateTime: event.startTime,
        endDateTime: event.endTime,
        description: this.getMeetingBody(event),
        location: getLocation(event)
      };
      const headers = new Headers();
      headers.append("x-revert-api-token", this.revertApiKey);
      headers.append("x-revert-t-id", this.tenantId);
      headers.append("Content-Type", "application/json");
      const eventBody = JSON.stringify(eventPayload);
      const requestOptions = {
        method: "PATCH",
        headers,
        body: eventBody
      };
      return await fetch(`${this.revertApiUrl}crm/events/${uid}`, requestOptions);
    };
    this.deleteMeeting = async (uid) => {
      const headers = new Headers();
      headers.append("x-revert-api-token", this.revertApiKey);
      headers.append("x-revert-t-id", this.tenantId);
      const requestOptions = {
        method: "DELETE",
        headers
      };
      return await fetch(`${this.revertApiUrl}crm/events/${uid}`, requestOptions);
    };
    this.revertApiKey = process.env.REVERT_API_KEY || "";
    this.revertApiUrl = process.env.REVERT_API_URL || "https://api.revert.dev/";
    this.tenantId = String(credential.teamId ? credential.teamId : credential.userId);
    this.log = logger.getSubLogger({ prefix: [`[[lib] ${appConfig.slug}`] });
  }
  async createContacts(contactsToCreate) {
    const result = contactsToCreate.map(async (attendee) => {
      const headers = new Headers();
      headers.append("x-revert-api-token", this.revertApiKey);
      headers.append("x-revert-t-id", this.tenantId);
      headers.append("Content-Type", "application/json");
      const [firstname, lastname] = !!attendee.name ? attendee.name.split(" ") : [attendee.email, "-"];
      const bodyRaw = JSON.stringify({
        firstName: firstname,
        lastName: lastname || "-",
        email: attendee.email
      });
      const requestOptions = {
        method: "POST",
        headers,
        body: bodyRaw
      };
      try {
        const response = await fetch(`${this.revertApiUrl}crm/contacts`, requestOptions);
        const result2 = await response.json();
        return result2;
      } catch (error) {
        return Promise.reject(error);
      }
    });
    const results = await Promise.all(result);
    return results.map((result2) => result2.result);
  }
  async getContacts({ emails }) {
    const emailArray = Array.isArray(emails) ? emails : [emails];
    const result = emailArray.map(async (attendeeEmail) => {
      const headers = new Headers();
      headers.append("x-revert-api-token", this.revertApiKey);
      headers.append("x-revert-t-id", this.tenantId);
      headers.append("Content-Type", "application/json");
      const bodyRaw = JSON.stringify({ searchCriteria: attendeeEmail });
      const requestOptions = {
        method: "POST",
        headers,
        body: bodyRaw
      };
      try {
        const response = await fetch(`${this.revertApiUrl}crm/contacts/search`, requestOptions);
        const result2 = await response.json();
        return result2;
      } catch (error) {
        return { status: "error", results: [] };
      }
    });
    const results = await Promise.all(result);
    return results[0].results;
  }
  async handleEventCreation(event, contacts) {
    const meetingEvent = await (await this.createPipedriveEvent(event, contacts)).json();
    if (meetingEvent && meetingEvent.status === "ok") {
      this.log.debug("event:creation:ok", { meetingEvent });
      return Promise.resolve({
        uid: meetingEvent.result.id,
        id: meetingEvent.result.id,
        type: appConfig.slug,
        password: "",
        url: "",
        additionalInfo: { contacts, meetingEvent }
      });
    }
    this.log.debug("meeting:creation:notOk", { meetingEvent, event, contacts });
    return Promise.reject("Something went wrong when creating a meeting in PipedriveCRM");
  }
  async createEvent(event, contacts) {
    return await this.handleEventCreation(event, contacts);
  }
  async updateEvent(uid, event) {
    const meetingEvent = await (await this.updateMeeting(uid, event)).json();
    if (meetingEvent && meetingEvent.status === "ok") {
      this.log.debug("event:updation:ok", { meetingEvent });
      return Promise.resolve({
        uid: meetingEvent.result.id,
        id: meetingEvent.result.id,
        type: appConfig.slug,
        password: "",
        url: "",
        additionalInfo: { meetingEvent }
      });
    }
    this.log.debug("meeting:updation:notOk", { meetingEvent, event });
    return Promise.reject("Something went wrong when updating a meeting in PipedriveCRM");
  }
  async deleteEvent(uid) {
    await this.deleteMeeting(uid);
  }
  async getAvailability(_dateFrom, _dateTo, _selectedCalendars) {
    return Promise.resolve([]);
  }
  async listCalendars(_event) {
    return Promise.resolve([]);
  }
  getAppOptions() {
    console.log("No options implemented");
  }
  async handleAttendeeNoShow() {
    console.log("Not implemented");
  }
}
export {
  PipedriveCrmService as default
};
