"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const index$2 = require("./user-OUg1A5rH.cjs");
const z = require("zod");
const querystring = require("querystring");
const defaultHandler = require("./defaultHandler-MSjhitc-.cjs");
const defaultResponder = require("./defaultResponder-6717TGqi.cjs");
const encodeOAuthState = require("./encodeOAuthState-VBfelnxQ.cjs");
const getServerSession = require("./getServerSession--MsbYy-1.cjs");
const getSafeRedirectUrl = require("./getSafeRedirectUrl-PsDZ4hOi.cjs");
const getInstalledAppPath = require("./getInstalledAppPath-JCXAHpgV.cjs");
const decodeOAuthState = require("./decodeOAuthState--7fljpCf.cjs");
const CalEventParser = require("./CalEventParser-rkr47M7A.cjs");
const huddle01AppKeySchema = z.z.object({
  identityToken: z.z.string()
});
async function storeHuddle01Credential(userId, identityToken) {
  const existingCredential = await index$2.prisma.credential.findFirst({
    where: {
      type: "huddle01_video",
      userId,
      appId: "huddle01"
    }
  });
  if (existingCredential) {
    await index$2.prisma.credential.update({
      where: { id: existingCredential.id },
      data: { key: { identityToken } }
    });
  } else {
    await index$2.prisma.credential.create({
      data: {
        type: "huddle01_video",
        key: { identityToken },
        userId,
        appId: "huddle01"
      }
    });
  }
}
async function getHuddle01Credential(userId) {
  const credential = await index$2.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 = index$2.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.encodeOAuthState(req);
  const params = {
    response_type: "code",
    redirect_uri: `${index$2.WEBAPP_URL}/api/integrations/huddle01video/callback`,
    state,
    appName: "Calcom"
  };
  const query = querystring.stringify(params);
  const url = `https://huddle01.app/thirdparty_auth?${query}`;
  return { url };
}
const add = defaultHandler.defaultHandler({
  GET: Promise.resolve({ default: defaultResponder.defaultResponder(handler$1) })
});
async function handler(req, res) {
  const session = await getServerSession.getServerSession({ req });
  const state = decodeOAuthState.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.getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath.getInstalledAppPath({ variant: "conferencing", slug: "huddle01" })
  );
}
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add,
  callback: handler
}, Symbol.toStringTag, { value: "Module" }));
exports.metadata = CalEventParser.metadata$2;
exports.api = index;
exports.lib = index$1;
