"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const querystring = require("querystring");
const z = require("zod");
const index$2 = require("./user-v6mfWQ2d.cjs");
const defaultHandler = require("./defaultHandler-MSjhitc-.cjs");
const defaultResponder = require("./defaultResponder-QWPOXt61.cjs");
const getAppKeysFromSlug = require("./getAppKeysFromSlug-W8EkKxxV.cjs");
const encodeOAuthState = require("./encodeOAuthState-VBfelnxQ.cjs");
const getSafeRedirectUrl = require("./getSafeRedirectUrl-ErDpjTNV.cjs");
const getInstalledAppPath = require("./getInstalledAppPath-3c7mqtrk.cjs");
const createOAuthAppCredential = require("./createOAuthAppCredential-ccvXpWYY.cjs");
const decodeOAuthState = require("./decodeOAuthState--7fljpCf.cjs");
const utils = require("./utils-U8_Jj24h.cjs");
const getBulkEventTypes = require("./getBulkEventTypes-bykT93wV.cjs");
const jellyAppKeysSchema = z.z.object({
  client_id: z.z.string(),
  client_secret: z.z.string()
});
const getJellyAppKeys = async () => {
  const appKeys = await getAppKeysFromSlug.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.encodeOAuthState(req);
  const params = {
    response_type: "code",
    app_id: client_id,
    redirect_uri: `${index$2.WEBAPP_URL}/api/integrations/jelly/callback`,
    state,
    scope: "write:jellies,read:user_email_phone"
  };
  const query = querystring.stringify(params);
  const url = `https://jellyjelly.com/login/oauth?${query}`;
  return { url };
}
const add = defaultHandler.defaultHandler({
  GET: Promise.resolve({ default: defaultResponder.defaultResponder(handler$1) })
});
const setDefaultConferencingApp = async (userId, appSlug) => {
  const eventTypes = await getBulkEventTypes.getBulkUserEventTypes(userId);
  const eventTypeIds = eventTypes.eventTypes.map((item) => item.id);
  const foundApp = utils.getAppFromSlug(appSlug);
  const appType = foundApp?.appData?.location?.type;
  if (!appType) {
    return;
  }
  const user = await index$2.prisma.user.findUnique({
    where: {
      id: userId
    },
    select: {
      metadata: true,
      credentials: true
    }
  });
  const currentMetadata = index$2.userMetadata.parse(user?.metadata);
  const credentialId = user?.credentials.find((item) => item.appId == appSlug)?.id;
  await index$2.prisma.user.update({
    where: {
      id: userId
    },
    data: {
      metadata: {
        ...currentMetadata,
        defaultConferencingApp: {
          appSlug
        }
      }
    }
  });
  await index$2.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.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.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 index$2.prisma.credential.deleteMany({
    where: {
      type: "jelly_conferencing",
      userId,
      appId: "jelly"
    }
  });
  await createOAuthAppCredential.createOAuthAppCredential(
    { appId: "jelly", type: "jelly_conferencing" },
    { access_token: responseBody.access_token },
    req
  );
  if (state?.defaultInstall) {
    setDefaultConferencingApp$1(userId, "jelly");
  }
  res.redirect(
    getSafeRedirectUrl.getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath.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" }));
exports.api = index$1;
exports.lib = index;
