import { p as prisma, Z as symmetricEncrypt, l as logger } from "./user--mpkKOwW.js";
import { g as getInstalledAppPath } from "./getInstalledAppPath-d831DYzR.js";
import { a as appConfig } from "./config-HtyzBhXE.js";
import { I as ICSFeedCalendarService } from "./CalendarService-pQmgd-Qz.js";
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  CalendarService: ICSFeedCalendarService
}, Symbol.toStringTag, { value: "Module" }));
async function handler(req, res) {
  if (req.method === "POST") {
    const { urls } = req.body;
    const user = await prisma.user.findFirstOrThrow({
      where: {
        id: req.session?.user?.id
      },
      select: {
        id: true,
        email: true
      }
    });
    const data = {
      type: appConfig.type,
      key: symmetricEncrypt(JSON.stringify({ urls }), process.env.CALENDSO_ENCRYPTION_KEY || ""),
      userId: user.id,
      teamId: null,
      appId: appConfig.slug,
      invalid: false,
      delegationCredentialId: null
    };
    try {
      const dav = new 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 prisma.credential.create({
        data
      });
    } catch (e) {
      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({ 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" }));
export {
  index as api,
  index$1 as lib
};
