"use strict";
const ICAL = require("ical.js");
const ics = require("ics");
const tsdav = require("tsdav");
const uuid = require("uuid");
const index = require("./orgDomains-W_rFTMBa.cjs");
const CalEventParser = require("./CalEventParser-XK6njYFX.cjs");
const dayjs = require("dayjs");
const sanitizeCalendarObject = (obj) => {
  return obj.data.replaceAll("\r\n", "\n").replaceAll("\r", "\n").replaceAll("\n ", "").replaceAll("\n	", "").replaceAll("\n", "\r\n").replaceAll(/(:[ \t]*\r\n[ \t]*:)/gm, ":").replaceAll(/(;[ \t]*\r\n[ \t]*;)/gm, ";").replaceAll(/(=[ \t]*\r\n[ \t]*=)/gm, "=");
};
const sanitizeCalendarObject$1 = sanitizeCalendarObject;
const TIMEZONE_FORMAT = "YYYY-MM-DDTHH:mm:ss[Z]";
const DEFAULT_CALENDAR_TYPE = "caldav";
const CALENDSO_ENCRYPTION_KEY = process.env.CALENDSO_ENCRYPTION_KEY || "";
function hasFileExtension(url) {
  const fileName = url.substring(url.lastIndexOf("/") + 1);
  return fileName.includes(".") && !fileName.substring(fileName.lastIndexOf(".")).includes("/");
}
function getFileExtension(url) {
  if (!hasFileExtension(url))
    return "ics";
  const fileName = url.substring(url.lastIndexOf("/") + 1);
  return fileName.substring(fileName.lastIndexOf(".") + 1);
}
const getTravelDurationInSeconds = (vevent, log) => {
  const travelDuration = vevent.getFirstPropertyValue("x-apple-travel-duration");
  if (!travelDuration)
    return 0;
  try {
    const travelSeconds = travelDuration.toSeconds();
    if (!Number.isInteger(travelSeconds))
      return 0;
    return travelSeconds;
  } catch (e) {
    log.error("invalid travelDuration?", e);
    return 0;
  }
};
const applyTravelDuration = (event, seconds) => {
  if (seconds <= 0)
    return event;
  event.startDate.second -= seconds;
  return event;
};
const convertDate = (date) => dayjs(date).utc().toArray().slice(0, 6).map((v, i) => i === 1 ? v + 1 : v);
const getDuration = (start, end) => ({
  minutes: dayjs(end).diff(dayjs(start), "minute")
});
const mapAttendees = (attendees) => attendees.map(({ email, name }) => ({ name, email, partstat: "NEEDS-ACTION" }));
class BaseCalendarService {
  constructor(credential, integrationName, url) {
    this.url = "";
    this.credentials = {};
    this.headers = {};
    this.integrationName = "";
    this.getUserTimezoneFromDB = async (id) => {
      const prisma = await Promise.resolve().then(() => require("./orgDomains-W_rFTMBa.cjs")).then((n) => n.index).then((mod) => mod.default);
      const user = await prisma.user.findUnique({
        where: {
          id
        },
        select: {
          timeZone: true
        }
      });
      return user?.timeZone;
    };
    this.getUserId = (selectedCalendars) => {
      if (selectedCalendars.length === 0) {
        return null;
      }
      return selectedCalendars[0].userId || null;
    };
    this.isValidFormat = (url2) => {
      const allowedExtensions = ["eml", "ics"];
      const urlExtension = getFileExtension(url2);
      if (!allowedExtensions.includes(urlExtension)) {
        console.error(`Unsupported calendar object format: ${urlExtension}`);
        return false;
      }
      return true;
    };
    this.integrationName = integrationName;
    const {
      username,
      password,
      url: credentialURL
    } = JSON.parse(index.symmetricDecrypt(credential.key, CALENDSO_ENCRYPTION_KEY));
    this.url = url || credentialURL;
    this.credentials = { username, password };
    this.headers = tsdav.getBasicAuthHeaders({ username, password });
    this.credential = credential;
    this.log = index.logger.getSubLogger({ prefix: [`[[lib] ${this.integrationName}`] });
  }
  getAttendees(event) {
    const attendees = mapAttendees(event.attendees);
    if (event.team?.members) {
      const teamAttendeesWithoutCurrentUser = event.team.members.filter(
        (member) => member.email !== this.credential.user?.email
      );
      attendees.push(...mapAttendees(teamAttendeesWithoutCurrentUser));
    }
    return attendees;
  }
  async createEvent(event, credentialId) {
    try {
      const calendars = await this.listCalendars(event);
      const uid = uuid.v4();
      const { error, value: iCalString } = ics.createEvent({
        uid,
        startInputType: "utc",
        start: convertDate(event.startTime),
        duration: getDuration(event.startTime, event.endTime),
        title: event.title,
        description: event.calendarDescription,
        location: CalEventParser.getLocation(event),
        organizer: { email: event.organizer.email, name: event.organizer.name },
        attendees: this.getAttendees(event),
        /** according to https://datatracker.ietf.org/doc/html/rfc2446#section-3.2.1, in a published iCalendar component.
         * "Attendees" MUST NOT be present
         * `attendees: this.getAttendees(event.attendees),`
         * [UPDATE]: Since we're not using the PUBLISH method to publish the iCalendar event and creating the event directly on iCal,
         * this shouldn't be an issue and we should be able to add attendees to the event right here.
         */
        ...event.hideCalendarEventDetails ? { classification: "PRIVATE" } : {}
      });
      if (error || !iCalString)
        throw new Error(`Error creating iCalString:=> ${error?.message} : ${error?.name} `);
      const mainHostDestinationCalendar = event.destinationCalendar ? event.destinationCalendar.find((cal) => cal.credentialId === credentialId) ?? event.destinationCalendar[0] : void 0;
      const responses = await Promise.all(
        calendars.filter(
          (c) => mainHostDestinationCalendar?.externalId ? c.externalId === mainHostDestinationCalendar.externalId : true
        ).map(
          (calendar) => tsdav.createCalendarObject({
            calendar: {
              url: calendar.externalId
            },
            filename: `${uid}.ics`,
            // according to https://datatracker.ietf.org/doc/html/rfc4791#section-4.1, Calendar object resources contained in calendar collections MUST NOT specify the iCalendar METHOD property.
            iCalString: iCalString.replace(/METHOD:[^\r\n]+\r\n/g, ""),
            headers: this.headers
          })
        )
      );
      if (responses.some((r) => !r.ok)) {
        throw new Error(
          `Error creating event: ${(await Promise.all(responses.map((r) => r.text()))).join(", ")}`
        );
      }
      return {
        uid,
        id: uid,
        type: this.integrationName,
        password: "",
        url: "",
        additionalInfo: {}
      };
    } catch (reason) {
      index.logger.error(reason);
      throw reason;
    }
  }
  async updateEvent(uid, event) {
    try {
      const events = await this.getEventsByUID(uid);
      const { error, value: iCalString } = ics.createEvent({
        uid,
        startInputType: "utc",
        start: convertDate(event.startTime),
        duration: getDuration(event.startTime, event.endTime),
        title: event.title,
        description: CalEventParser.getRichDescription(event),
        location: CalEventParser.getLocation(event),
        organizer: { email: event.organizer.email, name: event.organizer.name },
        attendees: this.getAttendees(event)
      });
      if (error) {
        this.log.debug("Error creating iCalString");
        return {
          uid,
          type: event.type,
          id: typeof event.uid === "string" ? event.uid : "-1",
          password: "",
          url: typeof event.location === "string" ? event.location : "-1",
          additionalInfo: {}
        };
      }
      let calendarEvent;
      const eventsToUpdate = events.filter((e) => e.uid === uid);
      return Promise.all(
        eventsToUpdate.map((eventItem) => {
          calendarEvent = eventItem;
          return tsdav.updateCalendarObject({
            calendarObject: {
              url: calendarEvent.url,
              // ensures compliance with standard iCal string (known as iCal2.0 by some) required by various providers
              data: iCalString?.replace(/METHOD:[^\r\n]+\r\n/g, ""),
              etag: calendarEvent?.etag
            },
            headers: this.headers
          });
        })
      ).then(
        (responses) => responses.map((response) => {
          if (response.status >= 200 && response.status < 300) {
            return {
              uid,
              type: this.credentials.type,
              id: typeof calendarEvent.uid === "string" ? calendarEvent.uid : "-1",
              password: "",
              url: calendarEvent.url,
              additionalInfo: typeof event.additionalInformation === "string" ? event.additionalInformation : {}
            };
          } else {
            this.log.error("Error: Status Code", response.status);
            return {
              uid,
              type: event.type,
              id: typeof event.uid === "string" ? event.uid : "-1",
              password: "",
              url: typeof event.location === "string" ? event.location : "-1",
              additionalInfo: typeof event.additionalInformation === "string" ? event.additionalInformation : {}
            };
          }
        })
      );
    } catch (reason) {
      this.log.error(reason);
      throw reason;
    }
  }
  async deleteEvent(uid) {
    try {
      const events = await this.getEventsByUID(uid);
      const eventsToDelete = events.filter((event) => event.uid === uid);
      await Promise.all(
        eventsToDelete.map((event) => {
          return tsdav.deleteCalendarObject({
            calendarObject: {
              url: event.url,
              etag: event?.etag
            },
            headers: this.headers
          });
        })
      );
    } catch (reason) {
      this.log.error(reason);
      throw reason;
    }
  }
  async getAvailability(dateFrom, dateTo, selectedCalendars) {
    const startISOString = new Date(dateFrom).toISOString();
    const objects = await this.fetchObjectsWithOptionalExpand({
      selectedCalendars,
      startISOString,
      dateTo,
      headers: this.headers
    });
    const userId = this.getUserId(selectedCalendars);
    const userTimeZone = userId ? await this.getUserTimezoneFromDB(userId) : "Europe/London";
    const events = [];
    objects.forEach((object) => {
      if (!object || object.data == null || JSON.stringify(object.data) == "{}")
        return;
      let vcalendar;
      try {
        const jcalData = ICAL.parse(sanitizeCalendarObject$1(object));
        vcalendar = new ICAL.Component(jcalData);
      } catch (e) {
        console.error("Error parsing calendar object: ", e);
        return;
      }
      const vevents = vcalendar.getAllSubcomponents("vevent");
      vevents.forEach((vevent) => {
        if (vevent?.getFirstPropertyValue("transp") === "TRANSPARENT")
          return;
        const event = new ICAL.Event(vevent);
        const dtstart = vevent?.getFirstPropertyValue("dtstart");
        const timezone = dtstart ? dtstart["timezone"] : void 0;
        const isUTC = timezone === "Z";
        const tzid = vevent?.getFirstPropertyValue("tzid") || isUTC ? "UTC" : timezone;
        if (!vcalendar.getFirstSubcomponent("vtimezone")) {
          const timezoneToUse = tzid || userTimeZone;
          if (timezoneToUse) {
            try {
              const timezoneComp = new ICAL.Component("vtimezone");
              timezoneComp.addPropertyWithValue("tzid", timezoneToUse);
              const standard = new ICAL.Component("standard");
              const tzoffsetfrom = dayjs(event.startDate.toJSDate()).tz(timezoneToUse).format("Z");
              const tzoffsetto = dayjs(event.endDate.toJSDate()).tz(timezoneToUse).format("Z");
              standard.addPropertyWithValue("tzoffsetfrom", tzoffsetfrom);
              standard.addPropertyWithValue("tzoffsetto", tzoffsetto);
              standard.addPropertyWithValue("dtstart", "1601-01-01T00:00:00");
              timezoneComp.addSubcomponent(standard);
              vcalendar.addSubcomponent(timezoneComp);
            } catch (e) {
              console.log("error in adding vtimezone", e);
            }
          } else {
            console.error("No timezone found");
          }
        }
        const vtimezone = vcalendar.getFirstSubcomponent("vtimezone");
        applyTravelDuration(event, getTravelDurationInSeconds(vevent, this.log));
        if (event.isRecurring()) {
          let maxIterations = 365;
          if (["HOURLY", "SECONDLY", "MINUTELY"].includes(event.getRecurrenceTypes())) {
            console.error(`Won't handle [${event.getRecurrenceTypes()}] recurrence`);
            return;
          }
          const start = dayjs(dateFrom);
          const end = dayjs(dateTo);
          const startDate = ICAL.Time.fromDateTimeString(startISOString);
          startDate.hour = event.startDate.hour;
          startDate.minute = event.startDate.minute;
          startDate.second = event.startDate.second;
          const iterator = event.iterator(startDate);
          let current;
          let currentEvent;
          let currentStart = null;
          let currentError;
          while (maxIterations > 0 && (currentStart === null || currentStart.isAfter(end) === false) && // this iterator was poorly implemented, normally done is expected to be
          // returned
          (current = iterator.next())) {
            maxIterations -= 1;
            try {
              currentEvent = event.getOccurrenceDetails(current);
            } catch (error) {
              if (error instanceof Error && error.message !== currentError) {
                currentError = error.message;
                this.log.error("error", error);
              }
            }
            if (!currentEvent)
              return;
            if (vtimezone) {
              const zone = new ICAL.Timezone(vtimezone);
              currentEvent.startDate = currentEvent.startDate.convertToZone(zone);
              currentEvent.endDate = currentEvent.endDate.convertToZone(zone);
            }
            currentStart = dayjs(currentEvent.startDate.toJSDate());
            if (currentStart.isBetween(start, end) === true) {
              events.push({
                start: currentStart.toISOString(),
                end: dayjs(currentEvent.endDate.toJSDate()).toISOString()
              });
            }
          }
          if (maxIterations <= 0) {
            console.warn("could not find any occurrence for recurring event in 365 iterations");
          }
          return;
        }
        if (vtimezone) {
          const zone = new ICAL.Timezone(vtimezone);
          event.startDate = event.startDate.convertToZone(zone);
          event.endDate = event.endDate.convertToZone(zone);
        }
        return events.push({
          start: dayjs(event.startDate.toJSDate()).toISOString(),
          end: dayjs(event.endDate.toJSDate()).toISOString()
        });
      });
    });
    return Promise.resolve(events);
  }
  async listCalendars(event) {
    try {
      const account = await this.getAccount();
      const calendars = await tsdav.fetchCalendars({
        account,
        headers: this.headers
      });
      return calendars.reduce((newCalendars, calendar) => {
        if (!calendar.components?.includes("VEVENT"))
          return newCalendars;
        const [mainHostDestinationCalendar] = event?.destinationCalendar ?? [];
        newCalendars.push({
          externalId: calendar.url,
          /** @url https://github.com/calcom/cal.com/issues/7186 */
          name: typeof calendar.displayName === "string" ? calendar.displayName : "",
          primary: mainHostDestinationCalendar?.externalId ? mainHostDestinationCalendar.externalId === calendar.url : false,
          integration: this.integrationName,
          email: this.credentials.username ?? ""
        });
        return newCalendars;
      }, []);
    } catch (reason) {
      index.logger.error(reason);
      throw reason;
    }
  }
  /**
   * The fetchObjectsWithOptionalExpand function is responsible for fetching calendar objects
   * from an array of selectedCalendars. It attempts to fetch objects with the expand option
   * alone such that it works if a calendar supports it. If any calendar object has an undefined 'data' property
   * and etag isn't undefined, the function makes a new request without the expand option to retrieve the data.
   * The result is a flattened array of calendar objects with the structure { url: ..., etag: ..., data: ...}.
   *
   * @param {Object} options - The options object containing the following properties:
   *   @param {IntegrationCalendar[]} options.selectedCalendars - An array of IntegrationCalendar objects to fetch data from.
   *   @param {string} options.startISOString - The start date of the date range to fetch events from, in ISO 8601 format.
   *   @param {string} options.dateTo - The end date of the date range to fetch events from.
   *   @param {Object} options.headers - Headers to be included in the API requests.
   * @returns {Promise<Array>} - A promise that resolves to a flattened array of calendar objects with the structure { url: ..., etag: ..., data: ...}.
   */
  async fetchObjectsWithOptionalExpand({
    selectedCalendars,
    startISOString,
    dateTo,
    headers
  }) {
    const filteredCalendars = selectedCalendars.filter((sc) => sc.externalId);
    const fetchPromises = filteredCalendars.map(async (sc) => {
      const response = await tsdav.fetchCalendarObjects({
        urlFilter: (url) => this.isValidFormat(url),
        calendar: {
          url: sc.externalId
        },
        headers,
        expand: true,
        timeRange: {
          start: startISOString,
          end: new Date(dateTo).toISOString()
        }
      });
      const processedResponse = await Promise.all(
        response.map(async (calendarObject) => {
          const calendarObjectHasEtag = calendarObject.etag !== void 0;
          const calendarObjectDataUndefined = calendarObject.data === void 0;
          if (calendarObjectDataUndefined && calendarObjectHasEtag) {
            const responseWithoutExpand = await tsdav.fetchCalendarObjects({
              urlFilter: (url) => this.isValidFormat(url),
              calendar: {
                url: sc.externalId
              },
              headers,
              expand: false,
              timeRange: {
                start: startISOString,
                end: new Date(dateTo).toISOString()
              }
            });
            return responseWithoutExpand.find(
              (obj) => obj.url === calendarObject.url && obj.etag === calendarObject.etag
            );
          }
          return calendarObject;
        })
      );
      return processedResponse;
    });
    const resolvedPromises = await Promise.allSettled(fetchPromises);
    const fulfilledPromises = resolvedPromises.filter(
      (promise) => promise.status === "fulfilled"
    );
    const flatResult = fulfilledPromises.map((promise) => promise.value).flat().filter((obj) => obj !== null);
    return flatResult;
  }
  async getEvents(calId, dateFrom, dateTo, objectUrls) {
    try {
      const objects = await tsdav.fetchCalendarObjects({
        calendar: {
          url: calId
        },
        objectUrls: objectUrls ? objectUrls : void 0,
        timeRange: dateFrom && dateTo ? {
          start: dayjs(dateFrom).utc().format(TIMEZONE_FORMAT),
          end: dayjs(dateTo).utc().format(TIMEZONE_FORMAT)
        } : void 0,
        headers: this.headers
      });
      const events = objects.filter((e) => !!e.data).map((object) => {
        const jcalData = ICAL.parse(sanitizeCalendarObject$1(object));
        const vcalendar = new ICAL.Component(jcalData);
        const vevent = vcalendar.getFirstSubcomponent("vevent");
        const event = new ICAL.Event(vevent);
        const calendarTimezone = vcalendar.getFirstSubcomponent("vtimezone")?.getFirstPropertyValue("tzid") || "";
        const startDate = calendarTimezone ? dayjs.tz(event.startDate.toString(), calendarTimezone) : new Date(event.startDate.toUnixTime() * 1e3);
        const endDate = calendarTimezone ? dayjs.tz(event.endDate.toString(), calendarTimezone) : new Date(event.endDate.toUnixTime() * 1e3);
        return {
          uid: event.uid,
          etag: object.etag,
          url: object.url,
          summary: event.summary,
          description: event.description,
          location: event.location,
          sequence: event.sequence,
          startDate,
          endDate,
          duration: {
            weeks: event.duration.weeks,
            days: event.duration.days,
            hours: event.duration.hours,
            minutes: event.duration.minutes,
            seconds: event.duration.seconds,
            isNegative: event.duration.isNegative
          },
          organizer: event.organizer,
          attendees: event.attendees.map((a) => a.getValues()),
          recurrenceId: event.recurrenceId,
          timezone: calendarTimezone
        };
      });
      return events;
    } catch (reason) {
      console.error(reason);
      throw reason;
    }
  }
  async getEventsByUID(uid) {
    const events = [];
    const calendars = await this.listCalendars();
    for (const cal of calendars) {
      const calEvents = await this.getEvents(cal.externalId, null, null, [`${cal.externalId}${uid}.ics`]);
      for (const ev of calEvents) {
        events.push(ev);
      }
    }
    return events;
  }
  async getAccount() {
    return tsdav.createAccount({
      account: {
        serverUrl: this.url,
        accountType: DEFAULT_CALENDAR_TYPE,
        credentials: this.credentials
      },
      headers: this.headers
    });
  }
}
exports.BaseCalendarService = BaseCalendarService;
