"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const querystring = require("querystring");
const index$2 = require("./index-QSf6WJj0.cjs");
const getAppKeysFromSlug = require("./getAppKeysFromSlug-duun9y1Q.cjs");
const encodeOAuthState = require("./encodeOAuthState-VBfelnxQ.cjs");
const getSafeRedirectUrl = require("./getSafeRedirectUrl-MkOChEjJ.cjs");
const getInstalledAppPath = require("./getInstalledAppPath-2GQAo7UC.cjs");
const createOAuthAppCredential = require("./createOAuthAppCredential--aER13Ig.cjs");
const decodeOAuthState = require("./decodeOAuthState--7fljpCf.cjs");
const z = require("zod");
const CalendarAppError = require("./CalendarAppError-RC_O0RpM.cjs");
const errors = require("./errors-fb9bpDY1.cjs");
const httpError = require("./http-error-mkY8Ke7V.cjs");
const getParsedAppKeysFromSlug = require("./getParsedAppKeysFromSlug-C26nE0Z-.cjs");
const markTokenAsExpired = require("./markTokenAsExpired-iyuDezo3.cjs");
const oAuthManagerHelper = require("./oAuthManagerHelper-fwylF2RU.cjs");
const index$3 = require("./email-manager-PJbiqghj.cjs");
const OFFICE365_VIDEO_SCOPES = ["OnlineMeetings.ReadWrite", "offline_access"];
async function handler$1(req, res) {
  if (req.method === "GET") {
    let clientId = "";
    const appKeys = await getAppKeysFromSlug.getAppKeysFromSlug("msteams");
    if (typeof appKeys.client_id === "string")
      clientId = appKeys.client_id;
    if (!clientId)
      return res.status(400).json({ message: "Office 365 client_id missing." });
    const state = encodeOAuthState.encodeOAuthState(req);
    const params = {
      response_type: "code",
      scope: OFFICE365_VIDEO_SCOPES.join(" "),
      client_id: clientId,
      redirect_uri: `${index$2.WEBAPP_URL_FOR_OAUTH}/api/integrations/office365video/callback`,
      state
    };
    const query = querystring.stringify(params);
    const url = `https://login.microsoftonline.com/common/oauth2/v2.0/authorize?${query}`;
    res.status(200).json({ url });
  }
}
async function handler(req, res) {
  const { code } = req.query;
  const state = decodeOAuthState.decodeOAuthState(req);
  if (typeof code !== "string") {
    if (state?.onErrorReturnTo || state?.returnTo) {
      res.redirect(
        getSafeRedirectUrl.getSafeRedirectUrl(state.onErrorReturnTo) ?? getSafeRedirectUrl.getSafeRedirectUrl(state?.returnTo) ?? `${index$2.WEBAPP_URL}/apps/installed`
      );
      return;
    }
    res.status(400).json({ message: "No code returned" });
    return;
  }
  let clientId = "";
  let clientSecret = "";
  const appKeys = await getAppKeysFromSlug.getAppKeysFromSlug("msteams");
  if (typeof appKeys.client_id === "string")
    clientId = appKeys.client_id;
  if (typeof appKeys.client_secret === "string")
    clientSecret = appKeys.client_secret;
  if (!clientId)
    return res.status(400).json({ message: "Office 365 client_id missing." });
  if (!clientSecret)
    return res.status(400).json({ message: "Office 365 client_secret missing." });
  const toUrlEncoded = (payload) => Object.keys(payload).map((key) => `${key}=${encodeURIComponent(payload[key])}`).join("&");
  const body = toUrlEncoded({
    client_id: clientId,
    grant_type: "authorization_code",
    code,
    scope: OFFICE365_VIDEO_SCOPES.join(" "),
    redirect_uri: `${index$2.WEBAPP_URL_FOR_OAUTH}/api/integrations/office365video/callback`,
    client_secret: clientSecret
  });
  const response = await fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
    },
    body
  });
  const responseBody = await response.json();
  if (!response.ok) {
    return res.redirect(`/apps/installed?error=${JSON.stringify(responseBody)}`);
  }
  const whoami = await fetch("https://graph.microsoft.com/v1.0/me", {
    headers: { Authorization: `Bearer ${responseBody.access_token}` }
  });
  const graphUser = await whoami.json();
  responseBody.email = graphUser.mail ?? graphUser.userPrincipalName;
  responseBody.expiry_date = Math.round(+/* @__PURE__ */ new Date() / 1e3 + responseBody.expires_in);
  delete responseBody.expires_in;
  const userId = req.session?.user.id;
  if (!userId) {
    return res.status(404).json({ message: "No user found" });
  }
  const existingCredentialOfficeVideo = await index$2.prisma.credential.findMany({
    select: {
      id: true
    },
    where: {
      type: "office365_video",
      userId: req.session?.user.id,
      appId: "msteams"
    }
  });
  const credentialIdsToDelete = existingCredentialOfficeVideo.map((item) => item.id);
  if (credentialIdsToDelete.length > 0) {
    await index$2.prisma.credential.deleteMany({ where: { id: { in: credentialIdsToDelete }, userId } });
  }
  await createOAuthAppCredential.createOAuthAppCredential({ appId: "msteams", type: "office365_video" }, responseBody, req);
  return res.redirect(
    getSafeRedirectUrl.getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath.getInstalledAppPath({ variant: "conferencing", slug: "msteams" })
  );
}
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add: handler$1,
  callback: handler
}, Symbol.toStringTag, { value: "Module" }));
const o365VideoAppKeysSchema = z.z.object({
  client_id: z.z.string(),
  client_secret: z.z.string()
});
const getO365VideoAppKeys = async () => {
  return getParsedAppKeysFromSlug.getParsedAppKeysFromSlug(index$3.config$2.slug, o365VideoAppKeysSchema);
};
const TeamsVideoApiAdapter = (credential) => {
  console.log("TeamsVideoApiAdapter--credential: ", credential);
  let azureUserId;
  const tokenResponse = oAuthManagerHelper.oAuthManagerHelper.getTokenObjectFromCredential(credential);
  const auth = new markTokenAsExpired.OAuthManager({
    credentialSyncVariables: oAuthManagerHelper.oAuthManagerHelper.credentialSyncVariables,
    resourceOwner: {
      type: "user",
      id: credential.userId
    },
    appSlug: index$3.config$2.slug,
    currentTokenObject: tokenResponse,
    fetchNewTokenObject: async ({ refreshToken }) => {
      const isDelegated = Boolean(credential?.delegatedTo);
      if (!isDelegated && !refreshToken) {
        return null;
      }
      const credentials = isDelegated ? {
        client_id: credential?.delegatedTo?.serviceAccountKey?.client_id,
        client_secret: credential?.delegatedTo?.serviceAccountKey?.private_key
      } : await getO365VideoAppKeys();
      if (isDelegated && (!credentials.client_id || !credentials.client_secret)) {
        throw new CalendarAppError.CalendarAppDelegationCredentialConfigurationError(
          "Delegation credential without clientId or Secret"
        );
      }
      const url = getAuthUrl(isDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
      const scope = isDelegated ? "https://graph.microsoft.com/.default" : OFFICE365_VIDEO_SCOPES.join(" ");
      const params = {
        scope,
        client_id: credentials.client_id || "",
        client_secret: credentials.client_secret || "",
        grant_type: isDelegated ? "client_credentials" : "refresh_token",
        ...isDelegated ? {} : { refresh_token: refreshToken ?? "" }
      };
      return await fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams(params)
      });
    },
    isTokenObjectUnusable: async function() {
      return null;
    },
    isAccessTokenUnusable: async function() {
      return null;
    },
    invalidateTokenObject: () => oAuthManagerHelper.oAuthManagerHelper.invalidateCredential(credential.id),
    expireAccessToken: () => oAuthManagerHelper.oAuthManagerHelper.markTokenAsExpired(credential),
    updateTokenObject: (tokenObject) => {
      if (!Boolean(credential.delegatedTo)) {
        return oAuthManagerHelper.oAuthManagerHelper.updateTokenObject({ tokenObject, credentialId: credential.id });
      }
      return Promise.resolve();
    }
  });
  function getAuthUrl(delegatedTo, tenantId) {
    if (delegatedTo) {
      if (!tenantId) {
        throw new CalendarAppError.CalendarAppDelegationCredentialInvalidGrantError(
          "Invalid DelegationCredential Settings: tenantId is missing"
        );
      }
      return `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
    }
    return "https://login.microsoftonline.com/common/oauth2/v2.0/token";
  }
  const translateEvent = (event) => {
    return {
      startDateTime: event.startTime,
      endDateTime: event.endTime,
      subject: event.title
    };
  };
  async function getAzureUserId(credential2) {
    if (azureUserId)
      return azureUserId;
    const isDelegated = Boolean(credential2?.delegatedTo);
    if (!isDelegated)
      return null;
    const url = getAuthUrl(isDelegated, credential2?.delegatedTo?.serviceAccountKey?.tenant_id);
    const delegationCredentialClientId = credential2.delegatedTo?.serviceAccountKey?.client_id;
    const delegationCredentialClientSecret = credential2.delegatedTo?.serviceAccountKey?.private_key;
    if (!delegationCredentialClientId || !delegationCredentialClientSecret) {
      throw new CalendarAppError.CalendarAppDelegationCredentialConfigurationError(
        "Delegation credential without clientId or Secret"
      );
    }
    const loginResponse = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({
        scope: "https://graph.microsoft.com/.default",
        client_id: delegationCredentialClientId,
        grant_type: "client_credentials",
        client_secret: delegationCredentialClientSecret
      })
    });
    const clonedResponse = loginResponse.clone();
    const parsedLoginResponse = await clonedResponse.json();
    const token = parsedLoginResponse?.access_token;
    const oauthClientIdAliasRegex = /\+[a-zA-Z0-9]{25}/;
    const email = credential2?.user?.email.replace(oauthClientIdAliasRegex, "");
    const encodedFilter = encodeURIComponent(`mail eq '${email}'`);
    const queryParams = `$filter=${encodedFilter}`;
    const response = await fetch(`https://graph.microsoft.com/v1.0/users?${queryParams}`, {
      method: "GET",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        Authorization: `Bearer ${token}`
      }
    });
    const parsedBody = await response.json();
    if (!parsedBody?.value?.[0]?.id) {
      throw new CalendarAppError.CalendarAppDelegationCredentialInvalidGrantError(
        "User might not exist in Microsoft Azure Active Directory"
      );
    }
    azureUserId = parsedBody.value[0].id;
    return azureUserId;
  }
  async function getUserEndpoint() {
    const azureUserId2 = await getAzureUserId(credential);
    return azureUserId2 ? `https://graph.microsoft.com/v1.0/users/${azureUserId2}` : "https://graph.microsoft.com/v1.0/me";
  }
  return {
    getAvailability: () => {
      return Promise.resolve([]);
    },
    updateMeeting: async (bookingRef, event) => {
      const resultString = await auth.requestRaw({
        url: `${await getUserEndpoint()}/onlineMeetings`,
        options: {
          method: "POST",
          body: JSON.stringify(translateEvent(event))
        }
      }).then(errors.handleErrorsRaw);
      const resultObject = JSON.parse(resultString);
      return Promise.resolve({
        type: "office365_video",
        id: resultObject.id,
        password: "",
        url: resultObject.joinWebUrl || resultObject.joinUrl
      });
    },
    deleteMeeting: () => {
      return Promise.resolve([]);
    },
    createMeeting: async (event) => {
      console.log("=======>createMeeting: ");
      const url = `${await getUserEndpoint()}/onlineMeetings`;
      console.log("urllllllllllll: ", url);
      console.log("translateEvent(event): ", translateEvent(event));
      const resultString = await auth.requestRaw({
        url,
        options: {
          method: "POST",
          body: JSON.stringify(translateEvent(event))
        }
      }).then(errors.handleErrorsRaw);
      const resultObject = JSON.parse(resultString);
      if (!resultObject.id || !resultObject.joinUrl || !resultObject.joinWebUrl) {
        throw new httpError.HttpError({
          statusCode: 500,
          message: `Error creating MS Teams meeting: ${resultObject.error.message}`
        });
      }
      return Promise.resolve({
        type: "office365_video",
        id: resultObject.id,
        password: "",
        url: resultObject.joinWebUrl || resultObject.joinUrl
      });
    }
  };
};
const TeamsVideoApiAdapter$1 = TeamsVideoApiAdapter;
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  VideoApiAdapter: TeamsVideoApiAdapter$1
}, Symbol.toStringTag, { value: "Module" }));
exports.api = index$1;
exports.lib = index;
