"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const short = require("short-uuid");
const uuid = require("uuid");
const CalEventParser = require("./CalEventParser-RR7nWuhu.cjs");
const z = require("zod");
const getAppKeysFromSlug = require("./getAppKeysFromSlug-tS_OdWJj.cjs");
const index = require("./i18n-HHdcQbuJ.cjs");
const piiFreeData = require("./piiFreeData-FAapPrV2.cjs");
const index$1 = require("./email-manager-W3dV0VZ2.cjs");
const dailyAppKeysSchema = z.z.object({
  api_key: z.z.string(),
  scale_plan: z.z.string().default("false")
});
const getDailyAppKeys = async () => {
  const appKeys = await getAppKeysFromSlug.getAppKeysFromSlug("daily-video");
  return dailyAppKeysSchema.parse(appKeys);
};
const VideoApiAdapterMap = process.env.NEXT_PUBLIC_IS_E2E === "1" ? {} : {
  dailyvideo: Promise.resolve().then(() => require("./VideoApiAdapter-HgAq1NrR.cjs")),
  huddle01video: Promise.resolve().then(() => require("./VideoApiAdapter-DmShITxM.cjs")),
  jelly: Promise.resolve().then(() => require("./VideoApiAdapter-ceLWaa_Y.cjs")),
  jitsivideo: Promise.resolve().then(() => require("./VideoApiAdapter-hgTPeiao.cjs")),
  nextcloudtalk: Promise.resolve().then(() => require("./VideoApiAdapter-qxnC6e1k.cjs")),
  office365video: Promise.resolve().then(() => require("./VideoApiAdapter-zdVuxeTm.cjs")),
  shimmervideo: Promise.resolve().then(() => require("./VideoApiAdapter-qOBCnpOD.cjs")),
  sylapsvideo: Promise.resolve().then(() => require("./VideoApiAdapter-Ks5ohfU9.cjs")),
  tandemvideo: Promise.resolve().then(() => require("./VideoApiAdapter-KZ-pUhtM.cjs")),
  webex: Promise.resolve().then(() => require("./VideoApiAdapter-tRSI2tYl.cjs")),
  zoomvideo: Promise.resolve().then(() => require("./VideoApiAdapter-ZOkIMEDy.cjs"))
};
const log = index.logger.getSubLogger({ prefix: ["[lib] videoClient"] });
const translator = short();
const getVideoAdapters = async (withCredentials) => {
  const videoAdapters = [];
  for (const cred of withCredentials) {
    const appName = cred.type.split("_").join("");
    log.silly("Getting video adapter for", index.safeStringify({ appName, cred: piiFreeData.getPiiFreeCredential(cred) }));
    let videoAdapterImport = VideoApiAdapterMap[appName];
    if (!videoAdapterImport) {
      const appTypeVariant = cred.type.substring(0, cred.type.lastIndexOf("_"));
      log.silly(`Adapter not found for ${appName}, trying fallback ${appTypeVariant}`);
      videoAdapterImport = VideoApiAdapterMap[appTypeVariant];
    }
    if (!videoAdapterImport) {
      log.error(`Couldn't get adapter for ${appName}`);
      continue;
    }
    const videoAdapterModule = await videoAdapterImport;
    const makeVideoApiAdapter = videoAdapterModule.default;
    if (makeVideoApiAdapter) {
      const videoAdapter = makeVideoApiAdapter(cred);
      videoAdapters.push(videoAdapter);
    } else {
      log.error(`App ${appName} doesn't have a default VideoApiAdapter export`);
    }
  }
  return videoAdapters;
};
const createMeeting = async (credential, calEvent) => {
  const uid = CalEventParser.getUid(calEvent);
  log.debug(
    "createMeeting",
    index.safeStringify({
      credential: piiFreeData.getPiiFreeCredential(credential),
      uid,
      calEvent: piiFreeData.getPiiFreeCalendarEvent(calEvent)
    })
  );
  if (!credential || !credential.appId) {
    throw new Error(
      "Credentials must be set! Video platforms are optional, so this method shouldn't even be called when no video credentials are set."
    );
  }
  const videoAdapters = await getVideoAdapters([credential]);
  const [firstVideoAdapter] = videoAdapters;
  let createdMeeting;
  let returnObject = {
    appName: credential.appId || "",
    type: credential.type,
    uid,
    originalEvent: calEvent,
    success: false,
    createdEvent: void 0,
    credentialId: credential.id
  };
  try {
    const enabledApp = await index.prisma.app.findUnique({
      where: {
        slug: credential.appId
      },
      select: {
        enabled: true
      }
    });
    if (!enabledApp?.enabled)
      throw `Location app ${credential.appId} is either disabled or not seeded at all`;
    createdMeeting = await firstVideoAdapter?.createMeeting(calEvent);
    returnObject = { ...returnObject, createdEvent: createdMeeting, success: true };
    log.debug("created Meeting", index.safeStringify(returnObject));
  } catch (err) {
    await index$1.sendBrokenIntegrationEmail(calEvent, "video");
    log.error(
      "createMeeting failed",
      index.safeStringify(err),
      index.safeStringify({ calEvent: piiFreeData.getPiiFreeCalendarEvent(calEvent) })
    );
    const defaultMeeting = await createMeetingWithCalVideo(calEvent);
    if (defaultMeeting) {
      calEvent.location = CalEventParser.DailyLocationType;
    }
    returnObject = { ...returnObject, originalEvent: calEvent, createdEvent: defaultMeeting };
  }
  return returnObject;
};
const updateMeeting = async (credential, calEvent, bookingRef) => {
  const uid = translator.fromUUID(uuid.v5(JSON.stringify(calEvent), uuid.v5.URL));
  let success = true;
  const [firstVideoAdapter] = await getVideoAdapters([credential]);
  const canCallUpdateMeeting = !!(credential && bookingRef);
  const updatedMeeting = canCallUpdateMeeting ? await firstVideoAdapter?.updateMeeting(bookingRef, calEvent).catch(async (e) => {
    await index$1.sendBrokenIntegrationEmail(calEvent, "video");
    log.error("updateMeeting failed", e, calEvent);
    success = false;
    return void 0;
  }) : void 0;
  if (!updatedMeeting) {
    log.error(
      "updateMeeting failed",
      index.safeStringify({ bookingRef, canCallUpdateMeeting, calEvent, credential })
    );
    return {
      appName: credential.appId || "",
      type: credential.type,
      success,
      uid,
      originalEvent: calEvent
    };
  }
  return {
    appName: credential.appId || "",
    type: credential.type,
    success,
    uid,
    updatedEvent: updatedMeeting,
    originalEvent: calEvent
  };
};
const deleteMeeting = async (credential, uid) => {
  if (credential) {
    const videoAdapter = (await getVideoAdapters([credential]))[0];
    log.debug(
      "Calling deleteMeeting for",
      index.safeStringify({ credential: piiFreeData.getPiiFreeCredential(credential), uid })
    );
    if (videoAdapter) {
      return videoAdapter.deleteMeeting(uid);
    }
  }
  return Promise.resolve({});
};
const createMeetingWithCalVideo = async (calEvent) => {
  let dailyAppKeys;
  try {
    dailyAppKeys = await getDailyAppKeys();
  } catch (e) {
    return;
  }
  const [videoAdapter] = await getVideoAdapters([
    {
      id: 0,
      appId: "daily-video",
      type: "daily_video",
      userId: null,
      user: { email: "" },
      teamId: null,
      key: dailyAppKeys,
      invalid: false,
      delegationCredentialId: null
    }
  ]);
  return videoAdapter?.createMeeting(calEvent);
};
const createInstantMeetingWithCalVideo = async (endTime) => {
  let dailyAppKeys;
  try {
    dailyAppKeys = await getDailyAppKeys();
  } catch (e) {
    return;
  }
  const [videoAdapter] = await getVideoAdapters([
    {
      id: 0,
      appId: "daily-video",
      type: "daily_video",
      userId: null,
      user: { email: "" },
      teamId: null,
      key: dailyAppKeys,
      invalid: false,
      delegationCredentialId: null
    }
  ]);
  return videoAdapter?.createInstantCalVideoRoom?.(endTime);
};
const getRecordingsOfCalVideoByRoomName = async (roomName) => {
  let dailyAppKeys;
  try {
    dailyAppKeys = await getDailyAppKeys();
  } catch (e) {
    console.error("Error: Cal video provider is not installed.");
    return;
  }
  const [videoAdapter] = await getVideoAdapters([
    {
      id: 0,
      appId: "daily-video",
      type: "daily_video",
      userId: null,
      user: { email: "" },
      teamId: null,
      key: dailyAppKeys,
      invalid: false,
      delegationCredentialId: null
    }
  ]);
  return videoAdapter?.getRecordings?.(roomName);
};
const getDownloadLinkOfCalVideoByRecordingId = async (recordingId) => {
  let dailyAppKeys;
  try {
    dailyAppKeys = await getDailyAppKeys();
  } catch (e) {
    console.error("Error: Cal video provider is not installed.");
    return;
  }
  const [videoAdapter] = await getVideoAdapters([
    {
      id: 0,
      appId: "daily-video",
      type: "daily_video",
      userId: null,
      user: { email: "" },
      teamId: null,
      key: dailyAppKeys,
      invalid: false,
      delegationCredentialId: null
    }
  ]);
  return videoAdapter?.getRecordingDownloadLink?.(recordingId);
};
const getAllTranscriptsAccessLinkFromRoomName = async (roomName) => {
  let dailyAppKeys;
  try {
    dailyAppKeys = await getDailyAppKeys();
  } catch (e) {
    console.error("Error: Cal video provider is not installed.");
    return;
  }
  const [videoAdapter] = await getVideoAdapters([
    {
      id: 0,
      appId: "daily-video",
      type: "daily_video",
      userId: null,
      user: { email: "" },
      teamId: null,
      key: dailyAppKeys,
      invalid: false,
      delegationCredentialId: null
    }
  ]);
  return videoAdapter?.getAllTranscriptsAccessLinkFromRoomName?.(roomName);
};
exports.createInstantMeetingWithCalVideo = createInstantMeetingWithCalVideo;
exports.createMeeting = createMeeting;
exports.deleteMeeting = deleteMeeting;
exports.getAllTranscriptsAccessLinkFromRoomName = getAllTranscriptsAccessLinkFromRoomName;
exports.getDailyAppKeys = getDailyAppKeys;
exports.getDownloadLinkOfCalVideoByRecordingId = getDownloadLinkOfCalVideoByRecordingId;
exports.getRecordingsOfCalVideoByRoomName = getRecordingsOfCalVideoByRoomName;
exports.updateMeeting = updateMeeting;
