import "./index-rbwdGzy0.js";
import { l as getErrorFromUnknown } from "./CalEventParser-ZzmnrFso.js";
import { H as HttpError } from "./http-error-RJXCPZV2.js";
import { B as BookingRepository } from "./booking-3Ajdl9qR.js";
import { p as prisma, f as withReporting } from "./user--mpkKOwW.js";
import { p as parseDurationLimit, a as ascendingLimitKeys, i as intervalLimitKeyToUnit, b as parseBookingLimit } from "./isBookingLimits-2AKB36r0.js";
import dayjs from "dayjs";
async function checkDurationLimits(durationLimits, eventStartDate, eventId, rescheduleUid) {
  const parsedDurationLimits = parseDurationLimit(durationLimits);
  if (!parsedDurationLimits)
    return false;
  const limitCalculations = ascendingLimitKeys.map(
    (key) => checkDurationLimit({
      key,
      limitingNumber: parsedDurationLimits[key],
      eventStartDate,
      eventId,
      rescheduleUid
    })
  );
  try {
    return !!await Promise.all(limitCalculations);
  } catch (error) {
    throw new HttpError({ message: getErrorFromUnknown(error).message, statusCode: 401 });
  }
}
async function checkDurationLimit({
  eventStartDate,
  eventId,
  key,
  limitingNumber,
  rescheduleUid
}) {
  {
    if (!limitingNumber)
      return;
    const unit = intervalLimitKeyToUnit(key);
    const startDate = dayjs(eventStartDate).startOf(unit).toDate();
    const endDate = dayjs(eventStartDate).endOf(unit).toDate();
    const bookingRepo = new BookingRepository(prisma);
    const totalBookingDuration = await bookingRepo.getTotalBookingDuration({
      eventId,
      startDate,
      endDate,
      rescheduleUid
    });
    if (totalBookingDuration < limitingNumber)
      return;
    throw new HttpError({
      message: `duration_limit_reached`,
      statusCode: 403
    });
  }
}
class CheckBookingAndDurationLimitsService {
  constructor(dependencies) {
    this.dependencies = dependencies;
    this.checkBookingAndDurationLimits = withReporting(
      this._checkBookingAndDurationLimits.bind(this),
      "checkBookingAndDurationLimits"
    );
  }
  async _checkBookingAndDurationLimits({ eventType, reqBodyStart, reqBodyRescheduleUid }) {
    if (Object.prototype.hasOwnProperty.call(eventType, "bookingLimits") || Object.prototype.hasOwnProperty.call(eventType, "durationLimits")) {
      const startAsDate = dayjs(reqBodyStart).toDate();
      if (eventType.bookingLimits && Object.keys(eventType.bookingLimits).length > 0) {
        await this.dependencies.checkBookingLimitsService.checkBookingLimits(
          eventType.bookingLimits,
          startAsDate,
          eventType.id,
          reqBodyRescheduleUid,
          eventType.schedule?.timeZone
        );
      }
      if (eventType.durationLimits) {
        await checkDurationLimits(
          eventType.durationLimits,
          startAsDate,
          eventType.id,
          reqBodyRescheduleUid
        );
      }
    }
  }
}
class CheckBookingLimitsService {
  constructor(dependencies) {
    this.dependencies = dependencies;
    this.checkBookingLimits = withReporting(this._checkBookingLimits.bind(this), "checkBookingLimits");
    this.checkBookingLimit = withReporting(this._checkBookingLimit.bind(this), "checkBookingLimit");
  }
  async _checkBookingLimits(bookingLimits, eventStartDate, eventId, rescheduleUid, timeZone, includeManagedEvents) {
    const parsedBookingLimits = parseBookingLimit(bookingLimits);
    if (!parsedBookingLimits)
      return false;
    const limitCalculations = ascendingLimitKeys.map(
      (key) => this.checkBookingLimit({
        key,
        limitingNumber: parsedBookingLimits[key],
        eventStartDate,
        eventId,
        timeZone,
        rescheduleUid,
        includeManagedEvents
      })
    );
    try {
      return !!await Promise.all(limitCalculations);
    } catch (error) {
      throw new HttpError({ message: getErrorFromUnknown(error).message, statusCode: 401 });
    }
  }
  async _checkBookingLimit({
    eventStartDate,
    eventId,
    key,
    limitingNumber,
    rescheduleUid,
    timeZone,
    teamId,
    user,
    includeManagedEvents = false
  }) {
    const eventDateInOrganizerTz = timeZone ? dayjs(eventStartDate).tz(timeZone) : dayjs(eventStartDate);
    if (!limitingNumber)
      return;
    const unit = intervalLimitKeyToUnit(key);
    const startDate = dayjs(eventDateInOrganizerTz).startOf(unit).toDate();
    const endDate = dayjs(eventDateInOrganizerTz).endOf(unit).toDate();
    let bookingsInPeriod;
    if (teamId && user) {
      bookingsInPeriod = await this.dependencies.bookingRepo.getAllAcceptedTeamBookingsOfUser({
        user: { id: user.id, email: user.email },
        teamId,
        startDate,
        endDate,
        shouldReturnCount: true,
        excludedUid: rescheduleUid,
        includeManagedEvents
      });
    } else {
      bookingsInPeriod = await this.dependencies.bookingRepo.countBookingsByEventTypeAndDateRange({
        eventTypeId: eventId,
        startDate,
        endDate,
        excludedUid: rescheduleUid
      });
    }
    if (bookingsInPeriod < limitingNumber)
      return;
    throw new HttpError({
      message: `booking_limit_reached`,
      statusCode: 403
    });
  }
}
export {
  CheckBookingLimitsService as C,
  CheckBookingAndDurationLimitsService as a
};
