"use strict";
const short = require("short-uuid");
const uuid = require("uuid");
const index = require("./index-QSf6WJj0.cjs");
const index$1 = require("./email-manager-PJbiqghj.cjs");
const indexBrowser = require("./index-browser-RtwB1hqI.cjs");
const dayjs = require("dayjs");
class CalendarEventClass {
  constructor(initProps) {
    Object.assign(this, initProps);
  }
}
const log$1 = index.logger.getSubLogger({ prefix: ["builders", "CalendarEvent", "builder"] });
const translator = short();
const userSelect = {
  select: {
    id: true,
    email: true,
    name: true,
    username: true,
    timeZone: true,
    credentials: true,
    bufferTime: true,
    destinationCalendar: true,
    locale: true
  }
};
class CalendarEventBuilder {
  constructor() {
    this.attendeesList = [];
    this.teamMembers = [];
    this.reset();
  }
  reset() {
    this.calendarEvent = new CalendarEventClass();
  }
  init(initProps) {
    this.calendarEvent = new CalendarEventClass(initProps);
  }
  setEventType(eventType) {
    this.eventType = eventType;
  }
  async buildEventObjectFromInnerClass(eventId) {
    const resultEvent = await this.getEventFromEventId(eventId);
    if (resultEvent) {
      this.eventType = resultEvent;
    }
  }
  async buildUsersFromInnerClass() {
    if (!this.eventType) {
      throw new Error("exec BuildEventObjectFromInnerClass before calling this function");
    }
    const users = this.eventType.users;
    if (!users.length && this.eventType.userId) {
      const eventTypeUser = await this.getUserById(this.eventType.userId);
      if (!eventTypeUser) {
        throw new Error("buildUsersFromINnerClass.eventTypeUser.notFound");
      }
      users.push(eventTypeUser);
    }
    this.setUsers(users);
  }
  buildAttendeesList() {
    this.attendeesList = [
      ...this.calendarEvent.attendees,
      ...this.teamMembers
    ];
  }
  async getUserById(userId) {
    let resultUser;
    try {
      resultUser = await index.prisma.user.findUniqueOrThrow({
        where: {
          id: userId
        },
        ...userSelect
      });
    } catch (error) {
      throw new Error("getUsersById.users.notFound");
    }
    return resultUser;
  }
  async getEventFromEventId(eventTypeId) {
    let resultEventType;
    try {
      resultEventType = await index.prisma.eventType.findUniqueOrThrow({
        where: {
          id: eventTypeId
        },
        select: {
          id: true,
          users: userSelect,
          team: {
            select: {
              id: true,
              name: true,
              slug: true
            }
          },
          description: true,
          slug: true,
          teamId: true,
          title: true,
          length: true,
          eventName: true,
          schedulingType: true,
          periodType: true,
          periodStartDate: true,
          periodEndDate: true,
          periodDays: true,
          periodCountCalendarDays: true,
          requiresConfirmation: true,
          userId: true,
          price: true,
          currency: true,
          metadata: true,
          destinationCalendar: true,
          hideCalendarNotes: true,
          hideCalendarEventDetails: true,
          disableCancelling: true,
          disableRescheduling: true
        }
      });
    } catch (error) {
      throw new Error("Error while getting eventType");
    }
    log$1.debug("getEventFromEventId.resultEventType", indexBrowser.safeStringify(resultEventType));
    return resultEventType;
  }
  async buildTeamMembers() {
    this.teamMembers = await this.getTeamMembers();
  }
  async getTeamMembers() {
    const teamMemberPromises = this.users.slice(1).map(async function(user) {
      return {
        id: user.id,
        username: user.username,
        email: user.email || "",
        // @NOTE: Should we change this "" to teamMemberId?
        name: user.name || "",
        timeZone: user.timeZone,
        language: {
          translate: await indexBrowser.getTranslation(user.locale ?? "en", "common"),
          locale: user.locale ?? "en"
        },
        locale: user.locale
      };
    });
    return await Promise.all(teamMemberPromises);
  }
  buildUIDCalendarEvent() {
    if (this.users && this.users.length > 0) {
      throw new Error("call buildUsers before calling this function");
    }
    const [mainOrganizer] = this.users;
    const seed = `${mainOrganizer.username}:${dayjs(this.calendarEvent.startTime).utc().format()}:${(/* @__PURE__ */ new Date()).getTime()}`;
    const uid = translator.fromUUID(uuid.v5(seed, uuid.v5.URL));
    this.calendarEvent.uid = uid;
  }
  setLocation(location) {
    this.calendarEvent.location = location;
  }
  setUId(uid) {
    this.calendarEvent.uid = uid;
  }
  setDestinationCalendar(destinationCalendar) {
    this.calendarEvent.destinationCalendar = destinationCalendar;
  }
  setHideCalendarNotes(hideCalendarNotes) {
    this.calendarEvent.hideCalendarNotes = hideCalendarNotes;
  }
  setHideCalendarEventDetails(hideCalendarEventDetails) {
    this.calendarEvent.hideCalendarEventDetails = hideCalendarEventDetails;
  }
  setDescription(description) {
    this.calendarEvent.description = description;
  }
  setNotes(notes) {
    this.calendarEvent.additionalNotes = notes;
  }
  setCancellationReason(cancellationReason) {
    this.calendarEvent.cancellationReason = cancellationReason;
  }
  setUsers(users) {
    this.users = users;
  }
  async setUsersFromId(userId) {
    let resultUser;
    try {
      resultUser = await index.prisma.user.findUniqueOrThrow({
        where: {
          id: userId
        },
        ...userSelect
      });
      this.setUsers([resultUser]);
    } catch (error) {
      throw new Error("getUsersById.users.notFound");
    }
  }
  buildRescheduleLink({
    allowRescheduleForCancelledBooking = false
  } = {}) {
    try {
      this.rescheduleLink = index$1.getRescheduleLink({
        calEvent: this.calendarEvent,
        allowRescheduleForCancelledBooking
      });
    } catch (error) {
      if (error instanceof Error) {
        throw new Error(`buildRescheduleLink.error: ${error.message}`);
      }
    }
  }
}
const log = index.logger.getSubLogger({ prefix: ["builders", "CalendarEvent", "director"] });
class CalendarEventDirector {
  setBuilder(builder) {
    this.builder = builder;
  }
  setExistingBooking(booking) {
    this.existingBooking = booking;
  }
  setCancellationReason(reason) {
    this.cancellationReason = reason;
  }
  async buildForRescheduleEmail({
    allowRescheduleForCancelledBooking = false
  } = {}) {
    if (this.existingBooking && this.existingBooking.eventTypeId && this.existingBooking.uid) {
      await this.builder.buildEventObjectFromInnerClass(this.existingBooking.eventTypeId);
      await this.builder.buildUsersFromInnerClass();
      this.builder.buildAttendeesList();
      this.builder.setLocation(this.existingBooking.location);
      this.builder.setUId(this.existingBooking.uid);
      this.builder.setCancellationReason(this.cancellationReason);
      this.builder.setDescription(this.builder.eventType.description);
      this.builder.setNotes(this.existingBooking.description);
      this.builder.buildRescheduleLink({ allowRescheduleForCancelledBooking });
      log.debug(
        "buildForRescheduleEmail",
        indexBrowser.safeStringify({ existingBooking: this.existingBooking, builder: this.builder })
      );
    } else {
      throw new Error("buildForRescheduleEmail.missing.params.required");
    }
  }
  async buildWithoutEventTypeForRescheduleEmail() {
    if (this.existingBooking && this.existingBooking.userId && this.existingBooking.uid) {
      await this.builder.setUsersFromId(this.existingBooking.userId);
      this.builder.buildAttendeesList();
      this.builder.setLocation(this.existingBooking.location);
      this.builder.setUId(this.existingBooking.uid);
      this.builder.setCancellationReason(this.cancellationReason);
      this.builder.setDescription(this.existingBooking.description);
      await this.builder.buildRescheduleLink();
    } else {
      throw new Error("buildWithoutEventTypeForRescheduleEmail.missing.params.required");
    }
  }
}
exports.CalendarEventBuilder = CalendarEventBuilder;
exports.CalendarEventDirector = CalendarEventDirector;
