"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const index$2 = require("./user-v6mfWQ2d.cjs");
const getInstalledAppPath = require("./getInstalledAppPath-3c7mqtrk.cjs");
const config = require("./config-HYZfW7_S.cjs");
const CalendarService = require("./CalendarService-ptkGC2Sc.cjs");
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  CalendarService: CalendarService.ICSFeedCalendarService
}, Symbol.toStringTag, { value: "Module" }));
async function handler(req, res) {
  if (req.method === "POST") {
    const { urls } = req.body;
    const user = await index$2.prisma.user.findFirstOrThrow({
      where: {
        id: req.session?.user?.id
      },
      select: {
        id: true,
        email: true
      }
    });
    const data = {
      type: config.appConfig.type,
      key: index$2.symmetricEncrypt(JSON.stringify({ urls }), process.env.CALENDSO_ENCRYPTION_KEY || ""),
      userId: user.id,
      teamId: null,
      appId: config.appConfig.slug,
      invalid: false,
      delegationCredentialId: null
    };
    try {
      const dav = new CalendarService.ICSFeedCalendarService({
        id: 0,
        ...data,
        user: { email: user.email }
      });
      const listedCals = await dav.listCalendars();
      if (listedCals.length !== urls.length) {
        throw new Error(`Listed cals and URLs mismatch: ${listedCals.length} vs. ${urls.length}`);
      }
      await index$2.prisma.credential.create({
        data
      });
    } catch (e) {
      index$2.logger.error("Could not add ICS feeds", e);
      return res.status(500).json({ message: "Could not add ICS feeds" });
    }
    return res.status(200).json({ url: getInstalledAppPath.getInstalledAppPath({ variant: "calendar", slug: "ics-feed" }) });
  }
  if (req.method === "GET") {
    return res.status(200).json({ url: "/apps/ics-feed/setup" });
  }
}
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add: handler
}, Symbol.toStringTag, { value: "Module" }));
exports.api = index;
exports.lib = index$1;
