"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const index$2 = require("./user-v6mfWQ2d.cjs");
const getInstalledAppPath = require("./getInstalledAppPath-3c7mqtrk.cjs");
const CalendarService = require("./CalendarService-sip5dFuM.cjs");
const _metadata = require("./_metadata-YQ5pmO_T.cjs");
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  CalendarService: CalendarService.AppleCalendarService
}, Symbol.toStringTag, { value: "Module" }));
async function handler(req, res) {
  if (req.method === "POST") {
    const { username, password } = req.body;
    const user = await index$2.prisma.user.findFirstOrThrow({
      where: {
        id: req.session?.user?.id
      },
      select: {
        email: true,
        id: true,
        credentials: {
          where: {
            type: "apple_calendar"
          }
        }
      }
    });
    let credentialExistsWithInputPassword = false;
    const credentialExistsWithUsername = user.credentials.find((credential) => {
      const decryptedCredential = JSON.parse(
        index$2.symmetricDecrypt(credential.key?.toString() || "", process.env.CALENDSO_ENCRYPTION_KEY || "")
      );
      if (decryptedCredential.username === username) {
        if (decryptedCredential.password === password) {
          credentialExistsWithInputPassword = true;
        }
        return true;
      }
    });
    if (credentialExistsWithInputPassword)
      return res.status(409).json({ message: "account_already_linked" });
    const data = {
      type: "apple_calendar",
      key: index$2.symmetricEncrypt(
        JSON.stringify({ username, password }),
        process.env.CALENDSO_ENCRYPTION_KEY || ""
      ),
      userId: user.id,
      teamId: null,
      appId: "apple-calendar",
      invalid: false
    };
    try {
      const dav = new CalendarService.AppleCalendarService({
        id: 0,
        ...data,
        user: { email: user.email },
        delegationCredentialId: null
      });
      await dav?.listCalendars();
      await index$2.prisma.credential.upsert({
        where: {
          id: credentialExistsWithUsername?.id ?? -1
        },
        create: data,
        update: data
      });
    } catch (reason) {
      index$2.logger.error("Could not add this apple calendar account", reason);
      return res.status(500).json({ message: "unable_to_add_apple_calendar" });
    }
    return res.status(200).json({ url: getInstalledAppPath.getInstalledAppPath({ variant: "calendar", slug: "apple-calendar" }) });
  }
  if (req.method === "GET") {
    return res.status(200).json({ url: "/apps/apple-calendar/setup" });
  }
}
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add: handler
}, Symbol.toStringTag, { value: "Module" }));
exports.metadata = _metadata.metadata;
exports.api = index;
exports.lib = index$1;
