import { stringify } from "querystring";
import { z } from "zod";
import { m as WEBAPP_URL, p as prisma } from "./index-Cw1zbw54.js";
import { d as defaultHandler } from "./defaultHandler-yvm7aMmf.js";
import { d as defaultResponder } from "./defaultResponder-s4VQhYfH.js";
import { g as getAppKeysFromSlug } from "./getAppKeysFromSlug-S62aYXii.js";
import { e as encodeOAuthState } from "./encodeOAuthState-ADe35aHB.js";
import { g as getSafeRedirectUrl } from "./getSafeRedirectUrl-hxmyPhEi.js";
import { g as getInstalledAppPath } from "./getInstalledAppPath-6P3H-VDB.js";
import { c as createOAuthAppCredential } from "./createOAuthAppCredential-UOwy2cXA.js";
import { d as decodeOAuthState } from "./decodeOAuthState-KhwGAxqw.js";
import { b as getAppFromSlug } from "./utils-tiDyn4ot.js";
import { g as getBulkUserEventTypes } from "./getBulkEventTypes-1AbuN40B.js";
import { F as userMetadata } from "./index-browser-c8sQ7p7S.js";
const jellyAppKeysSchema = z.object({
  client_id: z.string(),
  client_secret: z.string()
});
const getJellyAppKeys = async () => {
  const appKeys = await getAppKeysFromSlug("jelly");
  return jellyAppKeysSchema.parse(appKeys);
};
async function handler$1(req) {
  const user = req?.session?.user;
  if (!user) {
    return { status: 401, body: { error: "Unauthorized" } };
  }
  const { client_id } = await getJellyAppKeys();
  const state = encodeOAuthState(req);
  const params = {
    response_type: "code",
    app_id: client_id,
    redirect_uri: `${WEBAPP_URL}/api/integrations/jelly/callback`,
    state,
    scope: "write:jellies,read:user_email_phone"
  };
  const query = stringify(params);
  const url = `https://jellyjelly.com/login/oauth?${query}`;
  return { url };
}
const add = defaultHandler({
  GET: Promise.resolve({ default: defaultResponder(handler$1) })
});
const setDefaultConferencingApp = async (userId, appSlug) => {
  const eventTypes = await getBulkUserEventTypes(userId);
  const eventTypeIds = eventTypes.eventTypes.map((item) => item.id);
  const foundApp = getAppFromSlug(appSlug);
  const appType = foundApp?.appData?.location?.type;
  if (!appType) {
    return;
  }
  const user = await prisma.user.findUnique({
    where: {
      id: userId
    },
    select: {
      metadata: true,
      credentials: true
    }
  });
  const currentMetadata = userMetadata.parse(user?.metadata);
  const credentialId = user?.credentials.find((item) => item.appId == appSlug)?.id;
  await prisma.user.update({
    where: {
      id: userId
    },
    data: {
      metadata: {
        ...currentMetadata,
        defaultConferencingApp: {
          appSlug
        }
      }
    }
  });
  await prisma.eventType.updateMany({
    where: {
      id: {
        in: eventTypeIds
      },
      userId
    },
    data: {
      locations: [{ type: appType, credentialId }]
    }
  });
};
const setDefaultConferencingApp$1 = setDefaultConferencingApp;
async function handler(req, res) {
  const state = decodeOAuthState(req);
  const userId = req.session?.user.id;
  if (!userId) {
    return res.status(404).json({ message: "No user found" });
  }
  const { code } = req.query;
  const { client_id, client_secret } = await getAppKeysFromSlug("jelly");
  const result = await fetch(`https://www.jellyjelly.com/login/oauth/access_token`, {
    method: "POST",
    body: JSON.stringify({ code, client_id, client_secret })
  });
  if (result.status !== 200) {
    let errorMessage = "Something is wrong with the Jelly API";
    try {
      const responseBody2 = await result.json();
      errorMessage = responseBody2.error;
    } catch (e) {
    }
    res.status(400).json({ message: errorMessage });
    return;
  }
  const responseBody = await result.json();
  if (responseBody.error) {
    res.status(400).json({ message: responseBody.error });
    return;
  }
  await prisma.credential.deleteMany({
    where: {
      type: "jelly_conferencing",
      userId,
      appId: "jelly"
    }
  });
  await createOAuthAppCredential(
    { appId: "jelly", type: "jelly_conferencing" },
    { access_token: responseBody.access_token },
    req
  );
  if (state?.defaultInstall) {
    setDefaultConferencingApp$1(userId, "jelly");
  }
  res.redirect(
    getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath({ variant: "conferencing", slug: "jelly" })
  );
}
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add,
  callback: handler
}, Symbol.toStringTag, { value: "Module" }));
const JellyVideoApiAdapter = (credential) => {
  return {
    createMeeting: async (event) => {
      const keys = credential.key;
      const { access_token } = keys;
      const jellyLink = await fetch("https://www.jellyjelly.com/api/ti/start_jelly", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${access_token}`,
          "Content-Type": "application/json"
        }
      });
      const jellyLinkData = await jellyLink.json();
      return {
        type: "jelly_conferencing",
        id: jellyLinkData.talkId,
        password: "",
        url: jellyLinkData.url
      };
    },
    updateMeeting: async (bookingRef, event) => {
      return {
        type: "jelly_conferencing",
        id: bookingRef.externalCalendarId ? bookingRef.externalCalendarId : "",
        password: "",
        url: bookingRef.meetingUrl ? bookingRef.meetingUrl : ""
      };
    },
    deleteMeeting: async (uid) => {
      return {};
    },
    getAvailability: async (dateFrom, dateTo) => {
      return [];
    }
  };
};
const JellyVideoApiAdapter$1 = JellyVideoApiAdapter;
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  VideoApiAdapter: JellyVideoApiAdapter$1
}, Symbol.toStringTag, { value: "Module" }));
export {
  index$1 as api,
  index as lib
};
