import { z } from "zod";
import "./index-rbwdGzy0.js";
import { l as logger, a as safeStringify, A as APP_CREDENTIAL_SHARING_ENABLED, F as CREDENTIAL_SYNC_ENDPOINT, C as CREDENTIAL_SYNC_SECRET, o as CREDENTIAL_SYNC_SECRET_HEADER_NAME, p as prisma, G as Frequency } from "./i18n-tiaWqB1b.js";
import { g as getPiiFreeCalendarEvent } from "./piiFreeData-j9VT_8Gj.js";
import { g as getTokenObjectFromCredential, O as OAuthManager, i as invalidateCredential, m as markTokenAsExpired } from "./markTokenAsExpired-_H5_o27U.js";
import { j as metadata } from "./CalEventParser-tm9lJVKT.js";
import { g as getAppKeysFromSlug } from "./getAppKeysFromSlug-JDbO8QtR.js";
import dayjs from "dayjs";
const zoomAppKeysSchema = z.object({
  client_id: z.string(),
  client_secret: z.string()
});
const getZoomAppKeys = async () => {
  const appKeys = await getAppKeysFromSlug("zoom");
  return zoomAppKeysSchema.parse(appKeys);
};
const log = logger.getSubLogger({ prefix: ["app-store/zoomvideo/lib/VideoApiAdapter"] });
const zoomEventResultSchema = z.object({
  id: z.number(),
  join_url: z.string(),
  password: z.string().optional().default("")
});
const zoomMeetingsSchema = z.object({
  next_page_token: z.string(),
  page_count: z.number(),
  page_number: z.number(),
  page_size: z.number(),
  total_records: z.number(),
  meetings: z.array(
    z.object({
      agenda: z.string(),
      created_at: z.string(),
      duration: z.number(),
      host_id: z.string(),
      id: z.number(),
      join_url: z.string(),
      pmi: z.string(),
      start_time: z.string(),
      timezone: z.string(),
      topic: z.string(),
      type: z.number(),
      uuid: z.string()
    })
  )
});
const zoomUserSettingsSchema = z.object({
  recording: z.object({
    auto_recording: z.string().nullish()
  }).nullish(),
  schedule_meeting: z.object({
    default_password_for_scheduled_meetings: z.string().nullish()
  }).nullish(),
  in_meeting: z.object({
    waiting_room: z.boolean()
  }).nullish()
});
const settingsApiFilterResp = "default_password_for_scheduled_meetings,auto_recording,waiting_room";
const ZoomVideoApiAdapter = (credential) => {
  const tokenResponse = 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", safeStringify(err));
    }
    return userSettings;
  };
  const translateEvent = async (event) => {
    const getRecurrence = ({
      recurringEvent,
      startTime,
      attendees
    }) => {
      if (!recurringEvent) {
        return;
      }
      let recurrence2;
      switch (recurringEvent.freq) {
        case Frequency.DAILY:
          recurrence2 = {
            type: 1
          };
          break;
        case Frequency.WEEKLY:
          recurrence2 = {
            type: 2,
            weekly_days: dayjs(startTime).tz(attendees[0].timeZone).day() + 1
          };
          break;
        case 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).format("YYYY-MM-DDTHH:mm:ss"),
      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",
      safeStringify({
        error: safeStringify(error),
        // Log Raw response body here.
        responseBody: await clonedResponse.text(),
        status: clonedResponse.status
      })
    );
    return null;
  };
  const fetchZoomApi = async (endpoint, options) => {
    const auth = new OAuthManager({
      credentialSyncVariables: {
        APP_CREDENTIAL_SHARING_ENABLED,
        CREDENTIAL_SYNC_ENDPOINT,
        CREDENTIAL_SYNC_SECRET,
        CREDENTIAL_SYNC_SECRET_HEADER_NAME
      },
      resourceOwner: {
        type: "user",
        id: credential.userId
      },
      appSlug: metadata.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 = logger.getSubLogger({ prefix: ["zoomvideo:isTokenObjectUnusable"] });
        myLog.info(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(safeStringify({ responseBody }));
          if (responseBody.error === "invalid_grant") {
            return { reason: responseBody.error };
          }
        }
        return null;
      },
      isAccessTokenUnusable: async function(response) {
        const myLog = logger.getSubLogger({ prefix: ["zoomvideo:isAccessTokenUnusable"] });
        myLog.info(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(safeStringify({ responseBody }));
          if (responseBody.code === 124) {
            return { reason: responseBody.message ?? "" };
          }
        }
        return null;
      },
      invalidateTokenObject: () => invalidateCredential(credential.id),
      expireAccessToken: () => markTokenAsExpired(credential),
      updateTokenObject: async (newTokenObject) => {
        await prisma.credential.update({
          where: {
            id: credential.id
          },
          data: {
            // z.passthrough() is not allowed in Prisma, but we know this is trusted.
            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", 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",
          safeStringify({ error: safeStringify(err), event: 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",
          safeStringify({ error: err, event: getPiiFreeCalendarEvent(event) })
        );
        return Promise.reject(new Error("Failed to update meeting"));
      }
    }
  };
};
export {
  ZoomVideoApiAdapter as default,
  zoomMeetingsSchema,
  zoomUserSettingsSchema
};
