import { p as prisma, l as logger, J as WEBAPP_URL } from "./user--mpkKOwW.js";
import { z } from "zod";
import { stringify } from "querystring";
import { d as defaultHandler } from "./defaultHandler-yvm7aMmf.js";
import { d as defaultResponder } from "./defaultResponder-GZldAmhY.js";
import { e as encodeOAuthState } from "./encodeOAuthState-ADe35aHB.js";
import { getServerSession } from "./getServerSession-ZkQhIqnA.js";
import { g as getSafeRedirectUrl } from "./getSafeRedirectUrl-VGWYovUy.js";
import { g as getInstalledAppPath } from "./getInstalledAppPath-d831DYzR.js";
import { d as decodeOAuthState } from "./decodeOAuthState-KhwGAxqw.js";
import { z as z2 } from "./CalEventParser-ZzmnrFso.js";
const huddle01AppKeySchema = z.object({
  identityToken: z.string()
});
async function storeHuddle01Credential(userId, identityToken) {
  const existingCredential = await prisma.credential.findFirst({
    where: {
      type: "huddle01_video",
      userId,
      appId: "huddle01"
    }
  });
  if (existingCredential) {
    await prisma.credential.update({
      where: { id: existingCredential.id },
      data: { key: { identityToken } }
    });
  } else {
    await prisma.credential.create({
      data: {
        type: "huddle01_video",
        key: { identityToken },
        userId,
        appId: "huddle01"
      }
    });
  }
}
async function getHuddle01Credential(userId) {
  const credential = await prisma.credential.findFirst({
    where: {
      type: "huddle01_video",
      userId,
      appId: "huddle01"
    }
  });
  if (!credential) {
    throw new Error("Huddle01 credential not found");
  }
  return huddle01AppKeySchema.parse(credential?.key);
}
const API_END_POINT = "https://platform-api.huddle01.workers.dev/api/v2/calendar";
const fetchHuddleAPI = async (userId) => {
  const { identityToken } = await getHuddle01Credential(userId);
  const apiKey = process.env.HUDDLE01_API_TOKEN;
  if (!apiKey) {
    log.error("[Huddle01 Error] -> app key not found");
    throw new Error("Huddle01 app key not found");
  }
  const headers = {
    "x-api-key": apiKey,
    "x-identity-token": identityToken
  };
  return (endpoint, option) => {
    return fetch(`${API_END_POINT}/${endpoint}`, {
      ...option,
      headers: {
        ...option?.headers,
        ...headers
      }
    });
  };
};
const log = logger.getSubLogger({ prefix: ["app-store/huddle01video/lib/VideoApiAdapter"] });
const Huddle01ApiAdapter = (credential) => {
  return {
    createMeeting: async (e) => {
      if (!credential.userId) {
        log.error("[Huddle01 Error] -> User is not logged in");
        throw new Error("User is not logged in");
      }
      try {
        const fetch2 = await fetchHuddleAPI(credential.userId);
        const res = await fetch2("createMeeting", {
          method: "POST",
          body: JSON.stringify({
            title: e.title,
            startTime: e.startTime,
            endTime: e.endTime
          }),
          headers: {
            "Content-Type": "application/json"
          }
        });
        const data = await res.json();
        return {
          type: "huddle01_video",
          id: data.roomId,
          password: "",
          url: data.meetingLink
        };
      } catch (e2) {
        log.error("[Huddle01 Error] -> Error while creating meeeting", e2);
        throw Error("Error while creating meeting");
      }
    },
    updateMeeting: async (bookingRef, e) => {
      if (!credential.userId) {
        log.error("[Huddle01 Error] -> User is not logged in");
        throw new Error("User is not logged in");
      }
      const fetch2 = await fetchHuddleAPI(credential.userId);
      const res = await fetch2("updateMeeting", {
        method: "PUT",
        body: JSON.stringify({
          title: e.title,
          startTime: e.startTime,
          endTime: e.endTime,
          meetingId: bookingRef.uid
        }),
        headers: {
          "Content-Type": "application/json"
        }
      });
      const data = await res.json();
      return {
        type: "huddle01_video",
        id: data.roomId,
        password: "",
        url: data.meetingLink
      };
    },
    deleteMeeting: async (meetingId) => {
      if (!credential.userId) {
        log.error("[Huddle01 Error] -> User is not logged in");
        throw new Error("User is not logged in");
      }
      const fetch2 = await fetchHuddleAPI(credential.userId);
      const res = await fetch2("deleteMeeting", {
        method: "DELETE",
        body: JSON.stringify({
          meetingId
        }),
        headers: {
          "Content-Type": "application/json"
        }
      });
      const data = await res.json();
      return {
        type: "huddle01_video",
        id: data.roomId,
        password: "",
        url: data.meetingLink
      };
    },
    getAvailability: async () => {
      return [];
    }
  };
};
const Huddle01ApiAdapter$1 = Huddle01ApiAdapter;
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  VideoApiAdapter: Huddle01ApiAdapter$1
}, Symbol.toStringTag, { value: "Module" }));
async function handler$1(req) {
  const state = encodeOAuthState(req);
  const params = {
    response_type: "code",
    redirect_uri: `${WEBAPP_URL}/api/integrations/huddle01video/callback`,
    state,
    appName: "Calcom"
  };
  const query = stringify(params);
  const url = `https://huddle01.app/thirdparty_auth?${query}`;
  return { url };
}
const add = defaultHandler({
  GET: Promise.resolve({ default: defaultResponder(handler$1) })
});
async function handler(req, res) {
  const session = await getServerSession({ req });
  const state = decodeOAuthState(req);
  if (!session) {
    return res.status(401).json({ message: "Unauthorized" });
  }
  const userId = session.user.id;
  const { identityToken } = req.query;
  const token = Array.isArray(identityToken) ? identityToken[0] : identityToken;
  if (!token) {
    return res.status(401).json({
      message: "Something went wrong"
    });
  }
  await storeHuddle01Credential(userId, token);
  res.redirect(
    getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath({ variant: "conferencing", slug: "huddle01" })
  );
}
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add,
  callback: handler
}, Symbol.toStringTag, { value: "Module" }));
export {
  index as api,
  index$1 as lib,
  z2 as metadata
};
