"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const index$2 = require("./index-QSf6WJj0.cjs");
const getInstalledAppPath = require("./getInstalledAppPath-2GQAo7UC.cjs");
const queue = require("queue");
const z = require("zod");
const director = require("./director-T8Nq2GAR.cjs");
const indexBrowser = require("./index-browser-RtwB1hqI.cjs");
const videoClient = require("./videoClient-k_uXe0oj.cjs");
const getCalendar = require("./getCalendar-zHs4Z8rE.cjs");
const dayjs = require("dayjs");
const index$3 = require("./email-manager-PJbiqghj.cjs");
const _metadata = require("./_metadata-Z0TohRTT.cjs");
async function handler$1(req, res) {
  if (!req.session?.user?.id) {
    return res.status(401).json({ message: "You must be logged in to do this" });
  }
  const appType = "wipemycal_other";
  try {
    const alreadyInstalled = await index$2.prisma.credential.findFirst({
      where: {
        type: appType,
        userId: req.session.user.id
      }
    });
    if (alreadyInstalled) {
      throw new Error("Already installed");
    }
    const installation = await index$2.prisma.credential.create({
      data: {
        type: appType,
        key: {},
        userId: req.session.user.id,
        appId: "wipe-my-cal"
      }
    });
    if (!installation) {
      throw new Error("Unable to create user credential for wipe-my-cal");
    }
  } catch (error) {
    if (error instanceof Error) {
      return res.status(500).json({ message: error.message });
    }
    return res.status(500);
  }
  return res.status(200).json({ url: getInstalledAppPath.getInstalledAppPath({ variant: "other", slug: "wipe-my-cal" }) });
}
const Reschedule = async (bookingUid, cancellationReason) => {
  const bookingToReschedule = await index$2.prisma.booking.findFirstOrThrow({
    select: {
      id: true,
      uid: true,
      title: true,
      startTime: true,
      endTime: true,
      userId: true,
      eventTypeId: true,
      location: true,
      attendees: true,
      references: true,
      eventType: {
        select: {
          metadata: true,
          hideOrganizerEmail: true,
          team: {
            select: {
              id: true,
              name: true
            }
          }
        }
      },
      user: {
        select: {
          id: true,
          email: true,
          name: true,
          timeZone: true,
          locale: true,
          username: true,
          credentials: true,
          destinationCalendar: true
        }
      }
    },
    where: {
      uid: bookingUid,
      NOT: {
        status: {
          in: [index$2.BookingStatus.CANCELLED, index$2.BookingStatus.REJECTED]
        }
      }
    }
  });
  if (bookingToReschedule && bookingToReschedule.eventTypeId && bookingToReschedule.user) {
    const userOwner = bookingToReschedule.user;
    const event = await index$2.prisma.eventType.findUniqueOrThrow({
      select: {
        title: true,
        schedulingType: true
      },
      where: {
        id: bookingToReschedule.eventTypeId
      }
    });
    await index$2.prisma.booking.update({
      where: {
        id: bookingToReschedule.id
      },
      data: {
        rescheduled: true,
        cancellationReason,
        status: index$2.BookingStatus.CANCELLED,
        updatedAt: dayjs().toISOString()
      }
    });
    const [mainAttendee] = bookingToReschedule.attendees;
    const tAttendees = await indexBrowser.getTranslation(mainAttendee.locale ?? "en", "common");
    const usersToPeopleType = (users, selectedLanguage) => {
      return users?.map((user) => {
        return {
          email: user.email || "",
          name: user.name || "",
          username: user?.username || "",
          language: { translate: selectedLanguage, locale: user.locale || "en" },
          timeZone: user?.timeZone,
          phoneNumber: user?.phoneNumber
        };
      });
    };
    const userOwnerTranslation = await indexBrowser.getTranslation(userOwner.locale ?? "en", "common");
    const [userOwnerAsPeopleType] = usersToPeopleType([userOwner], userOwnerTranslation);
    const builder = new director.CalendarEventBuilder();
    builder.init({
      title: bookingToReschedule.title,
      type: event.title,
      startTime: bookingToReschedule.startTime.toISOString(),
      endTime: bookingToReschedule.endTime.toISOString(),
      attendees: usersToPeopleType(
        // username field doesn't exists on attendee but could be in the future
        bookingToReschedule.attendees,
        tAttendees
      ),
      organizer: userOwnerAsPeopleType,
      hideOrganizerEmail: bookingToReschedule.eventType?.hideOrganizerEmail,
      team: !!bookingToReschedule.eventType?.team ? {
        name: bookingToReschedule.eventType.team.name,
        id: bookingToReschedule.eventType.team.id,
        members: []
      } : void 0
    });
    const director$1 = new director.CalendarEventDirector();
    director$1.setBuilder(builder);
    director$1.setExistingBooking(bookingToReschedule);
    director$1.setCancellationReason(cancellationReason);
    await director$1.buildForRescheduleEmail();
    const credentialsMap = /* @__PURE__ */ new Map();
    userOwner.credentials.forEach((credential) => {
      credentialsMap.set(credential.type, credential);
    });
    const bookingRefsFiltered = bookingToReschedule.references.filter(
      (ref) => !!credentialsMap.get(ref.type)
    );
    const promises = bookingRefsFiltered.map(async (bookingRef) => {
      if (!bookingRef.uid)
        return;
      if (bookingRef.type.endsWith("_calendar")) {
        const calendar = await getCalendar.getCalendar(credentialsMap.get(bookingRef.type));
        return calendar?.deleteEvent(bookingRef.uid, builder.calendarEvent);
      } else if (bookingRef.type.endsWith("_video")) {
        return videoClient.deleteMeeting(credentialsMap.get(bookingRef.type), bookingRef.uid);
      }
    });
    try {
      await Promise.all(promises);
    } catch (error) {
      if (error instanceof Error) {
        index$2.logger.error(error.message);
      }
    }
    try {
      await index$3.sendRequestRescheduleEmailAndSMS(
        builder.calendarEvent,
        {
          rescheduleLink: builder.rescheduleLink
        },
        bookingToReschedule?.eventType?.metadata
      );
    } catch (error) {
      if (error instanceof Error) {
        index$2.logger.error(error.message);
      }
    }
    return true;
  }
};
const Reschedule$1 = Reschedule;
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  Reschedule: Reschedule$1
}, Symbol.toStringTag, { value: "Module" }));
const wipeMyCalendarBodySchema = z.z.object({
  initialDate: z.z.string(),
  endDate: z.z.string()
});
const handler = async (req, res) => {
  if (!req.session?.user?.id) {
    return res.status(401).json({ message: "You must be logged in to do this" });
  }
  try {
    const { initialDate, endDate } = req.body;
    const todayBookings = await index$2.prisma.booking.findMany({
      where: {
        startTime: {
          gte: initialDate
        },
        endTime: {
          lte: endDate
        },
        status: {
          in: [index$2.BookingStatus.ACCEPTED, index$2.BookingStatus.PENDING]
        },
        userId: req.session.user.id
      },
      select: {
        id: true,
        uid: true,
        status: true
      }
    });
    const q = queue({ results: [] });
    if (todayBookings.length > 0) {
      todayBookings.forEach(
        (booking) => q.push(() => {
          return Reschedule$1(booking.uid, "");
        })
      );
    }
    await q.start();
  } catch (error) {
    if (error instanceof Error) {
      return res.status(500).json({ message: error.message });
    }
    return res.status(500);
  }
  return res.status(200).json({ success: true });
};
function validate(handler2) {
  return async (req, res) => {
    if (req.method === "POST") {
      try {
        wipeMyCalendarBodySchema.parse(req.body);
      } catch (error) {
        if (error instanceof z.ZodError && error?.name === "ZodError") {
          return res.status(400).json(error?.issues);
        }
        return res.status(402);
      }
    } else {
      return res.status(405);
    }
    await handler2(req, res);
  };
}
const wipe = validate(handler);
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add: handler$1,
  wipe
}, Symbol.toStringTag, { value: "Module" }));
exports.metadata = _metadata.metadata;
exports.api = index;
exports.lib = index$1;
