import { p as prisma, s as symmetricDecrypt, u as symmetricEncrypt, l as logger } from "./index-Cw1zbw54.js";
import { g as getInstalledAppPath } from "./getInstalledAppPath-6P3H-VDB.js";
import { A as AppleCalendarService } from "./CalendarService-GvW3JnK-.js";
import { m } from "./_metadata-5fduS9fA.js";
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  CalendarService: AppleCalendarService
}, Symbol.toStringTag, { value: "Module" }));
async function handler(req, res) {
  if (req.method === "POST") {
    const { username, password } = req.body;
    const user = await 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(
        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: symmetricEncrypt(
        JSON.stringify({ username, password }),
        process.env.CALENDSO_ENCRYPTION_KEY || ""
      ),
      userId: user.id,
      teamId: null,
      appId: "apple-calendar",
      invalid: false
    };
    try {
      const dav = new AppleCalendarService({
        id: 0,
        ...data,
        user: { email: user.email },
        delegationCredentialId: null
      });
      await dav?.listCalendars();
      await prisma.credential.upsert({
        where: {
          id: credentialExistsWithUsername?.id ?? -1
        },
        create: data,
        update: data
      });
    } catch (reason) {
      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({ 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" }));
export {
  index as api,
  index$1 as lib,
  m as metadata
};
