import { h as handleErrorsJson, a as handleErrorsRaw } from "./CalEventParser-gVLQw-Bk.js";
import { H as HttpError } from "./http-error-RJXCPZV2.js";
import { p as prisma } from "./i18n-49-r55rr.js";
import { g as getAppKeysFromSlug } from "./getAppKeysFromSlug-Td0Hkihg.js";
const loadConfiguration = async () => {
  const appKeys = await getAppKeysFromSlug("tandem");
  let clientId = "";
  let clientSecret = "";
  let baseUrl = "";
  if (typeof appKeys.client_id === "string")
    clientId = appKeys.client_id;
  if (typeof appKeys.client_secret === "string")
    clientSecret = appKeys.client_secret;
  if (typeof appKeys.base_url === "string")
    baseUrl = appKeys.base_url;
  if (!clientId)
    throw new HttpError({ statusCode: 400, message: "Tandem client_id missing." });
  if (!clientSecret)
    throw new HttpError({ statusCode: 400, message: "Tandem client_secret missing." });
  if (!baseUrl)
    throw new HttpError({ statusCode: 400, message: "Tandem base_url missing." });
  return {
    clientId,
    clientSecret,
    baseUrl
  };
};
const tandemAuth = async (credential) => {
  const configuration = await loadConfiguration();
  const credentialKey = credential.key;
  const isTokenValid = (token) => token && token.access_token && token.expiry_date < Date.now();
  const refreshAccessToken = async (refreshToken) => {
    const result = await fetch(`${configuration.baseUrl}/api/v1/oauth/v2/token`, {
      method: "POST",
      body: new URLSearchParams({
        client_id: configuration.clientId,
        client_secret: configuration.clientSecret,
        code: refreshToken
      })
    });
    const responseBody = await handleErrorsJson(result);
    responseBody.expiry_date = Math.round(Date.now() + (responseBody.expires_in || 0) * 1e3);
    delete responseBody.expires_in;
    await prisma.credential.update({
      where: {
        id: credential.id
      },
      data: {
        key: responseBody
      }
    });
    credentialKey.expiry_date = responseBody.expiry_date;
    credentialKey.access_token = responseBody.access_token;
    credentialKey.refresh_token = responseBody.refresh_token;
    return credentialKey.access_token;
  };
  return {
    getToken: () => !isTokenValid(credentialKey) ? Promise.resolve(credentialKey.access_token) : refreshAccessToken(credentialKey.refresh_token)
  };
};
const TandemVideoApiAdapter = (credential) => {
  const auth = tandemAuth(credential);
  const _parseDate = (date) => {
    return Date.parse(date) / 1e3;
  };
  const _translateEvent = (event, param) => {
    return JSON.stringify({
      [param]: {
        title: event.title,
        starts_at: _parseDate(event.startTime),
        ends_at: _parseDate(event.endTime),
        description: event.description || "",
        conference_solution: "tandem",
        type: 3
      }
    });
  };
  const _translateResult = (result) => {
    return {
      type: "tandem_video",
      id: result.data.id,
      password: "",
      url: result.data.event_link
    };
  };
  return {
    /** Tandem doesn't need to return busy times, so we return empty */
    getAvailability: () => {
      return Promise.resolve([]);
    },
    createMeeting: async (event) => {
      const accessToken = await (await auth).getToken();
      const configuration = await loadConfiguration();
      const result = await fetch(`${configuration.baseUrl}/api/v1/meetings`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${accessToken}`,
          "Content-Type": "application/json"
        },
        body: _translateEvent(event, "meeting")
      });
      const responseBody = await handleErrorsJson(result);
      return Promise.resolve(_translateResult(responseBody));
    },
    deleteMeeting: async (uid) => {
      const accessToken = await (await auth).getToken();
      const configuration = await loadConfiguration();
      await fetch(`${configuration.baseUrl}/api/v1/meetings/${uid}`, {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${accessToken}`
        }
      }).then(handleErrorsRaw);
      return Promise.resolve();
    },
    updateMeeting: async (bookingRef, event) => {
      const accessToken = await (await auth).getToken();
      const configuration = await loadConfiguration();
      const result = await fetch(`${configuration.baseUrl}/api/v1/meetings/${bookingRef.meetingId}`, {
        method: "PUT",
        headers: {
          Authorization: `Bearer ${accessToken}`,
          "Content-Type": "application/json"
        },
        body: _translateEvent(event, "updates")
      });
      const responseBody = await handleErrorsJson(result);
      return Promise.resolve(_translateResult(responseBody));
    }
  };
};
export {
  TandemVideoApiAdapter as default
};
