"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const z = require("zod");
require("./index-Br7AzmuA.cjs");
const index = require("./i18n-Bs8xJzoY.cjs");
const piiFreeData = require("./piiFreeData-FAapPrV2.cjs");
const markTokenAsExpired = require("./markTokenAsExpired-JTzOdd4i.cjs");
const CalEventParser = require("./CalEventParser-mh8lC_8R.cjs");
const getAppKeysFromSlug = require("./getAppKeysFromSlug-vtOs9dbX.cjs");
const dayjs = require("dayjs");
const zoomAppKeysSchema = z.z.object({
  client_id: z.z.string(),
  client_secret: z.z.string()
});
const getZoomAppKeys = async () => {
  const appKeys = await getAppKeysFromSlug.getAppKeysFromSlug("zoom");
  return zoomAppKeysSchema.parse(appKeys);
};
const log = index.logger.getSubLogger({ prefix: ["app-store/zoomvideo/lib/VideoApiAdapter"] });
const zoomEventResultSchema = z.z.object({
  id: z.z.number(),
  join_url: z.z.string(),
  password: z.z.string().optional().default("")
});
const zoomMeetingsSchema = z.z.object({
  next_page_token: z.z.string(),
  page_count: z.z.number(),
  page_number: z.z.number(),
  page_size: z.z.number(),
  total_records: z.z.number(),
  meetings: z.z.array(
    z.z.object({
      agenda: z.z.string(),
      created_at: z.z.string(),
      duration: z.z.number(),
      host_id: z.z.string(),
      id: z.z.number(),
      join_url: z.z.string(),
      pmi: z.z.string(),
      start_time: z.z.string(),
      timezone: z.z.string(),
      topic: z.z.string(),
      type: z.z.number(),
      uuid: z.z.string()
    })
  )
});
const zoomUserSettingsSchema = z.z.object({
  recording: z.z.object({
    auto_recording: z.z.string().nullish()
  }).nullish(),
  schedule_meeting: z.z.object({
    default_password_for_scheduled_meetings: z.z.string().nullish()
  }).nullish(),
  in_meeting: z.z.object({
    waiting_room: z.z.boolean()
  }).nullish()
});
const settingsApiFilterResp = "default_password_for_scheduled_meetings,auto_recording,waiting_room";
const ZoomVideoApiAdapter = (credential) => {
  const tokenResponse = markTokenAsExpired.getTokenObjectFromCredential(credential);
  const getUserSettings = async () => {
    let userSettings;
    try {
      const responseBody = await fetchZoomApi(
        `users/me/settings?custom_query_fields=${settingsApiFilterResp}`
      );
      userSettings = zoomUserSettingsSchema.parse(responseBody);
    } catch (err) {
      log.error("Failed to retrieve zoom user settings", index.safeStringify(err));
    }
    return userSettings;
  };
  const translateEvent = async (event) => {
    const getRecurrence = ({
      recurringEvent,
      startTime,
      attendees
    }) => {
      if (!recurringEvent) {
        return;
      }
      let recurrence2;
      switch (recurringEvent.freq) {
        case index.Frequency.DAILY:
          recurrence2 = {
            type: 1
          };
          break;
        case index.Frequency.WEEKLY:
          recurrence2 = {
            type: 2,
            weekly_days: dayjs(startTime).tz(attendees[0].timeZone).day() + 1
          };
          break;
        case index.Frequency.MONTHLY:
          recurrence2 = {
            type: 3,
            monthly_day: dayjs(startTime).tz(attendees[0].timeZone).date()
          };
          break;
        default:
          return;
      }
      recurrence2.repeat_interval = recurringEvent.interval;
      if (recurringEvent.until) {
        recurrence2.end_date_time = recurringEvent.until.toISOString();
      } else {
        recurrence2.end_times = recurringEvent.count;
      }
      return {
        recurrence: {
          ...recurrence2
        }
      };
    };
    const truncateAgenda = (description) => {
      if (!description)
        return description;
      const maxLength = 1900;
      const trimmed = description.trimEnd();
      if (trimmed.length > maxLength) {
        return `${trimmed.substring(0, maxLength).trimEnd()}...`;
      }
      return trimmed;
    };
    const userSettings = await getUserSettings();
    const recurrence = getRecurrence(event);
    const waitingRoomEnabled = userSettings?.in_meeting?.waiting_room ?? false;
    return {
      topic: event.title,
      type: 2,
      // Means that this is a scheduled meeting
      start_time: dayjs(event.startTime).utc().format(),
      duration: (new Date(event.endTime).getTime() - new Date(event.startTime).getTime()) / 6e4,
      //schedule_for: "string",   TODO: Used when scheduling the meeting for someone else (needed?)
      timezone: event.organizer.timeZone,
      password: userSettings?.schedule_meeting?.default_password_for_scheduled_meetings ?? void 0,
      agenda: truncateAgenda(event.description),
      settings: {
        host_video: true,
        participant_video: true,
        cn_meeting: false,
        // TODO: true if host meeting in China
        in_meeting: false,
        // TODO: true if host meeting in India
        join_before_host: !waitingRoomEnabled,
        mute_upon_entry: false,
        watermark: false,
        use_pmi: false,
        approval_type: 2,
        audio: "both",
        auto_recording: userSettings?.recording?.auto_recording || "none",
        enforce_login: false,
        registrants_email_notification: true,
        waiting_room: waitingRoomEnabled
      },
      ...recurrence
    };
  };
  const handleZoomResponseJsonParseError = async ({
    error,
    clonedResponse
  }) => {
    log.error(
      "Error in JSON parsing Zoom API response",
      index.safeStringify({
        error: index.safeStringify(error),
        // Log Raw response body here.
        responseBody: await clonedResponse.text(),
        status: clonedResponse.status
      })
    );
    return null;
  };
  const fetchZoomApi = async (endpoint, options) => {
    const auth = new markTokenAsExpired.OAuthManager({
      credentialSyncVariables: {
        APP_CREDENTIAL_SHARING_ENABLED: index.APP_CREDENTIAL_SHARING_ENABLED,
        CREDENTIAL_SYNC_ENDPOINT: index.CREDENTIAL_SYNC_ENDPOINT,
        CREDENTIAL_SYNC_SECRET: index.CREDENTIAL_SYNC_SECRET,
        CREDENTIAL_SYNC_SECRET_HEADER_NAME: index.CREDENTIAL_SYNC_SECRET_HEADER_NAME
      },
      resourceOwner: {
        type: "user",
        id: credential.userId
      },
      appSlug: CalEventParser.metadata$1.slug,
      currentTokenObject: tokenResponse,
      fetchNewTokenObject: async ({ refreshToken }) => {
        if (!refreshToken) {
          return null;
        }
        const clientCredentials = await getZoomAppKeys();
        const { client_id, client_secret } = clientCredentials;
        const authHeader = `Basic ${Buffer.from(`${client_id}:${client_secret}`).toString("base64")}`;
        return fetch("https://zoom.us/oauth/token", {
          method: "POST",
          headers: {
            Authorization: authHeader,
            "Content-Type": "application/x-www-form-urlencoded"
          },
          body: new URLSearchParams({
            refresh_token: refreshToken,
            grant_type: "refresh_token"
          })
        });
      },
      isTokenObjectUnusable: async function(response) {
        const myLog = index.logger.getSubLogger({ prefix: ["zoomvideo:isTokenObjectUnusable"] });
        myLog.info(index.safeStringify({ status: response.status, ok: response.ok }));
        if (!response.ok) {
          let responseBody;
          const responseToUseInCaseOfError = response.clone();
          try {
            responseBody = await response.json();
          } catch (e) {
            return await handleZoomResponseJsonParseError({
              error: e,
              clonedResponse: responseToUseInCaseOfError
            });
          }
          myLog.debug(index.safeStringify({ responseBody }));
          if (responseBody.error === "invalid_grant") {
            return { reason: responseBody.error };
          }
        }
        return null;
      },
      isAccessTokenUnusable: async function(response) {
        const myLog = index.logger.getSubLogger({ prefix: ["zoomvideo:isAccessTokenUnusable"] });
        myLog.info(index.safeStringify({ status: response.status, ok: response.ok }));
        if (!response.ok) {
          let responseBody;
          const responseToUseInCaseOfError = response.clone();
          try {
            responseBody = await response.json();
          } catch (e) {
            return await handleZoomResponseJsonParseError({
              error: e,
              clonedResponse: responseToUseInCaseOfError
            });
          }
          myLog.debug(index.safeStringify({ responseBody }));
          if (responseBody.code === 124) {
            return { reason: responseBody.message ?? "" };
          }
        }
        return null;
      },
      invalidateTokenObject: () => markTokenAsExpired.invalidateCredential(credential.id),
      expireAccessToken: () => markTokenAsExpired.markTokenAsExpired(credential),
      updateTokenObject: async (newTokenObject) => {
        await index.prisma.credential.update({
          where: {
            id: credential.id
          },
          data: {
            key: newTokenObject
          }
        });
      }
    });
    const { json } = await auth.request({
      url: `https://api.zoom.us/v2/${endpoint}`,
      options: {
        method: "GET",
        ...options,
        headers: {
          ...options?.headers
        }
      }
    });
    return json;
  };
  return {
    getAvailability: async () => {
      try {
        const responseBody = await fetchZoomApi("users/me/meetings?type=scheduled&page_size=300");
        const data = zoomMeetingsSchema.parse(responseBody);
        return data.meetings.map((meeting) => ({
          start: meeting.start_time,
          end: new Date(new Date(meeting.start_time).getTime() + meeting.duration * 6e4).toISOString()
        }));
      } catch (err) {
        log.error("Failed to get availability", index.safeStringify(err));
        return [];
      }
    },
    createMeeting: async (event) => {
      try {
        const response = await fetchZoomApi("users/me/meetings", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(await translateEvent(event))
        });
        const result = zoomEventResultSchema.parse(response);
        if (result.id && result.join_url) {
          return {
            type: "zoom_video",
            id: result.id.toString(),
            password: result.password || "",
            url: result.join_url
          };
        }
        throw new Error(`Failed to create meeting. Response is ${JSON.stringify(result)}`);
      } catch (err) {
        log.error(
          "Zoom meeting creation failed",
          index.safeStringify({ error: index.safeStringify(err), event: piiFreeData.getPiiFreeCalendarEvent(event) })
        );
        throw new Error("Unexpected error");
      }
    },
    deleteMeeting: async (uid) => {
      try {
        await fetchZoomApi(`meetings/${uid}`, {
          method: "DELETE"
        });
        return Promise.resolve();
      } catch (err) {
        return Promise.reject(new Error("Failed to delete meeting"));
      }
    },
    updateMeeting: async (bookingRef, event) => {
      try {
        await fetchZoomApi(`meetings/${bookingRef.uid}`, {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(await translateEvent(event))
        });
        const updatedMeeting = await fetchZoomApi(`meetings/${bookingRef.uid}`);
        const result = zoomEventResultSchema.parse(updatedMeeting);
        return {
          type: "zoom_video",
          id: result.id.toString(),
          password: result.password || "",
          url: result.join_url
        };
      } catch (err) {
        log.error(
          "Failed to update meeting",
          index.safeStringify({ error: err, event: piiFreeData.getPiiFreeCalendarEvent(event) })
        );
        return Promise.reject(new Error("Failed to update meeting"));
      }
    }
  };
};
exports.default = ZoomVideoApiAdapter;
exports.zoomMeetingsSchema = zoomMeetingsSchema;
exports.zoomUserSettingsSchema = zoomUserSettingsSchema;
