"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
const defaultHandler = require("./defaultHandler-MSjhitc-.cjs");
const ewsJavascriptApi = require("ews-javascript-api");
const index$3 = require("./orgDomains-W_rFTMBa.cjs");
const add = defaultHandler.defaultHandler({
  GET: Promise.resolve().then(() => require("./_getAdd-uEM_Zwse.cjs")),
  POST: Promise.resolve().then(() => require("./_postAdd-gZX05gCl.cjs"))
});
const index$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add
}, Symbol.toStringTag, { value: "Module" }));
var ExchangeAuthentication = /* @__PURE__ */ ((ExchangeAuthentication2) => {
  ExchangeAuthentication2[ExchangeAuthentication2["STANDARD"] = 0] = "STANDARD";
  ExchangeAuthentication2[ExchangeAuthentication2["NTLM"] = 1] = "NTLM";
  return ExchangeAuthentication2;
})(ExchangeAuthentication || {});
var ExchangeVersion = /* @__PURE__ */ ((ExchangeVersion2) => {
  ExchangeVersion2[ExchangeVersion2["Exchange2007_SP1"] = 0] = "Exchange2007_SP1";
  ExchangeVersion2[ExchangeVersion2["Exchange2010"] = 1] = "Exchange2010";
  ExchangeVersion2[ExchangeVersion2["Exchange2010_SP1"] = 2] = "Exchange2010_SP1";
  ExchangeVersion2[ExchangeVersion2["Exchange2010_SP2"] = 3] = "Exchange2010_SP2";
  ExchangeVersion2[ExchangeVersion2["Exchange2013"] = 4] = "Exchange2013";
  ExchangeVersion2[ExchangeVersion2["Exchange2013_SP1"] = 5] = "Exchange2013_SP1";
  ExchangeVersion2[ExchangeVersion2["Exchange2015"] = 6] = "Exchange2015";
  ExchangeVersion2[ExchangeVersion2["Exchange2016"] = 7] = "Exchange2016";
  return ExchangeVersion2;
})(ExchangeVersion || {});
class ExchangeCalendarService {
  constructor(credential) {
    this.integrationName = "";
    this.integrationName = "exchange_calendar";
    this.log = index$3.logger.getSubLogger({ prefix: [`[[lib] ${this.integrationName}`] });
    this.payload = JSON.parse(
      index$3.symmetricDecrypt(credential.key?.toString() || "", process.env.CALENDSO_ENCRYPTION_KEY || "")
    );
  }
  async createEvent(event) {
    const appointment = new ewsJavascriptApi.Appointment(await this.getExchangeService());
    appointment.Subject = event.title;
    appointment.Start = ewsJavascriptApi.DateTime.Parse(event.startTime);
    appointment.End = ewsJavascriptApi.DateTime.Parse(event.endTime);
    appointment.Location = event.location || "";
    appointment.Body = new ewsJavascriptApi.MessageBody(event.description || "");
    event.attendees.forEach((attendee) => {
      appointment.RequiredAttendees.Add(new ewsJavascriptApi.Attendee(attendee.email));
    });
    if (event.team?.members) {
      event.team.members.forEach((member) => {
        appointment.RequiredAttendees.Add(new ewsJavascriptApi.Attendee(member.email));
      });
    }
    return appointment.Save(ewsJavascriptApi.SendInvitationsMode.SendToAllAndSaveCopy).then(() => {
      return {
        uid: appointment.Id.UniqueId,
        id: appointment.Id.UniqueId,
        password: "",
        type: "",
        url: "",
        additionalInfo: {}
      };
    }).catch((reason) => {
      this.log.error(reason);
      throw reason;
    });
  }
  async updateEvent(uid, event) {
    const appointment = await ewsJavascriptApi.Appointment.Bind(await this.getExchangeService(), new ewsJavascriptApi.ItemId(uid));
    appointment.Subject = event.title;
    appointment.Start = ewsJavascriptApi.DateTime.Parse(event.startTime);
    appointment.End = ewsJavascriptApi.DateTime.Parse(event.endTime);
    appointment.Location = event.location || "";
    appointment.Body = new ewsJavascriptApi.MessageBody(event.description || "");
    event.attendees.forEach((attendee) => {
      appointment.RequiredAttendees.Add(new ewsJavascriptApi.Attendee(attendee.email));
    });
    if (event.team?.members) {
      event.team.members.forEach((member) => {
        appointment.RequiredAttendees.Add(new ewsJavascriptApi.Attendee(member.email));
      });
    }
    return appointment.Update(
      ewsJavascriptApi.ConflictResolutionMode.AlwaysOverwrite,
      ewsJavascriptApi.SendInvitationsOrCancellationsMode.SendToChangedAndSaveCopy
    ).then(() => {
      return {
        uid: appointment.Id.UniqueId,
        id: appointment.Id.UniqueId,
        password: "",
        type: "",
        url: "",
        additionalInfo: {}
      };
    }).catch((reason) => {
      this.log.error(reason);
      throw reason;
    });
  }
  async deleteEvent(uid) {
    const appointment = await ewsJavascriptApi.Appointment.Bind(await this.getExchangeService(), new ewsJavascriptApi.ItemId(uid));
    return appointment.Delete(ewsJavascriptApi.DeleteMode.MoveToDeletedItems).catch((reason) => {
      this.log.error(reason);
      throw reason;
    });
  }
  async getAvailability(dateFrom, dateTo, selectedCalendars) {
    const calendars = await this.listCalendars();
    const promises = calendars.filter((lcal) => selectedCalendars.some((rcal) => lcal.externalId == rcal.externalId)).map(async (calendar) => {
      return (await this.getExchangeService()).FindAppointments(
        new ewsJavascriptApi.FolderId(calendar.externalId),
        new ewsJavascriptApi.CalendarView(ewsJavascriptApi.DateTime.Parse(dateFrom), ewsJavascriptApi.DateTime.Parse(dateTo))
      ).then((results) => {
        return results.Items.filter((appointment) => {
          return appointment.LegacyFreeBusyStatus != ewsJavascriptApi.LegacyFreeBusyStatus.Free;
        }).map((appointment) => {
          return {
            start: new Date(appointment.Start.ToISOString()),
            end: new Date(appointment.End.ToISOString())
          };
        });
      }).catch((reason) => {
        this.log.error(reason);
        throw reason;
      });
    });
    return Promise.all(promises).then((x) => x.flat());
  }
  async listCalendars() {
    const service = await this.getExchangeService();
    const view = new ewsJavascriptApi.FolderView(1e3);
    view.PropertySet = new ewsJavascriptApi.PropertySet(ewsJavascriptApi.BasePropertySet.IdOnly);
    view.PropertySet.Add(ewsJavascriptApi.FolderSchema.ParentFolderId);
    view.PropertySet.Add(ewsJavascriptApi.FolderSchema.DisplayName);
    view.PropertySet.Add(ewsJavascriptApi.FolderSchema.ChildFolderCount);
    view.Traversal = ewsJavascriptApi.FolderTraversal.Deep;
    const deletedItemsFolder = await ewsJavascriptApi.Folder.Bind(service, ewsJavascriptApi.WellKnownFolderName.DeletedItems);
    const searchFilterCollection = new ewsJavascriptApi.SearchFilter.SearchFilterCollection(ewsJavascriptApi.LogicalOperator.And);
    searchFilterCollection.Add(new ewsJavascriptApi.SearchFilter.IsEqualTo(ewsJavascriptApi.FolderSchema.FolderClass, "IPF.Appointment"));
    return service.FindFolders(ewsJavascriptApi.WellKnownFolderName.MsgFolderRoot, searchFilterCollection, view).then((res) => {
      return res.Folders.filter((folder) => {
        return folder.ParentFolderId.UniqueId != deletedItemsFolder.Id.UniqueId;
      }).map((folder) => {
        return {
          externalId: folder.Id.UniqueId,
          name: folder.DisplayName ?? "",
          primary: folder.ChildFolderCount > 0,
          integration: this.integrationName
        };
      });
    }).catch((reason) => {
      this.log.error(reason);
      throw reason;
    });
  }
  async getExchangeService() {
    const service = new ewsJavascriptApi.ExchangeService(this.payload.exchangeVersion);
    service.Credentials = new ewsJavascriptApi.WebCredentials(this.payload.username, this.payload.password);
    service.Url = new ewsJavascriptApi.Uri(this.payload.url);
    if (this.payload.authenticationMethod === ExchangeAuthentication.NTLM) {
      const { XhrApi } = await import("@ewsjs/xhr");
      const xhr = new XhrApi({
        rejectUnauthorized: false
      }).useNtlmAuthentication(this.payload.username, this.payload.password);
      service.XHRApi = xhr;
    }
    return service;
  }
}
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  CalendarService: ExchangeCalendarService
}, Symbol.toStringTag, { value: "Module" }));
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  api: index$2,
  lib: index$1
}, Symbol.toStringTag, { value: "Module" }));
exports.ExchangeAuthentication = ExchangeAuthentication;
exports.ExchangeCalendarService = ExchangeCalendarService;
exports.ExchangeVersion = ExchangeVersion;
exports.index = index;
