"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const querystring = require("querystring");
const uuid = require("uuid");
const z = require("zod");
const index = require("./i18n-Bs8xJzoY.cjs");
const getAppKeysFromSlug = require("./getAppKeysFromSlug-vtOs9dbX.cjs");
const getParsedAppKeysFromSlug = require("./getParsedAppKeysFromSlug-6Fd-SXzu.cjs");
const markTokenAsExpired = require("./markTokenAsExpired-JTzOdd4i.cjs");
const oAuthManagerHelper = require("./oAuthManagerHelper-ipQc7KO6.cjs");
const CalEventParser = require("./CalEventParser-mh8lC_8R.cjs");
const nextcloudEventResultSchema = z.z.object({
  ocs: z.z.object({
    meta: z.z.object({
      status: z.z.string(),
      statuscode: z.z.number(),
      message: z.z.string()
    }),
    data: z.z.object({
      token: z.z.string()
    })
  })
});
const NextcloudTalkVideoApiAdapter = (credential) => {
  const tokenResponse = oAuthManagerHelper.oAuthManagerHelper.getTokenObjectFromCredential(credential);
  const clientCredentials = getParsedAppKeysFromSlug.getParsedAppKeysFromSlug(CalEventParser.config.slug, index.appKeysSchema);
  const fetchNextcloudApi = async (endpoint, options) => {
    const auth = new markTokenAsExpired.OAuthManager({
      credentialSyncVariables: oAuthManagerHelper.oAuthManagerHelper.credentialSyncVariables,
      resourceOwner: {
        type: "user",
        id: credential.userId
      },
      appSlug: CalEventParser.config.slug,
      currentTokenObject: tokenResponse,
      fetchNewTokenObject: async ({ refreshToken }) => {
        const { nextcloudTalkClientId, nextcloudTalkClientSecret, nextcloudTalkHost: nextcloudTalkHost2 } = await clientCredentials;
        if (!refreshToken) {
          return null;
        }
        const params = {
          client_id: nextcloudTalkClientId,
          client_secret: nextcloudTalkClientSecret,
          refresh_token: refreshToken,
          grant_type: "refresh_token"
        };
        const query = querystring.stringify(params);
        return fetch(`${nextcloudTalkHost2}/index.php/apps/oauth2/api/v1/token?${query}`, {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
          },
          body: new URLSearchParams({})
        });
      },
      isTokenObjectUnusable: async function(response) {
        const myLog = index.logger.getSubLogger({ prefix: ["nextcloudtalkvideo:isTokenObjectUnusable"] });
        myLog.debug(index.safeStringify({ status: response.status, ok: response.ok }));
        if (!response.ok || response.status < 200 && response.status >= 300) {
          const responseBody = await response.json();
          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: ["nextcloudtalkvideo:isAccessTokenUnusable"] });
        myLog.debug(index.safeStringify({ status: response.status, ok: response.ok }));
        if (!response.ok || response.status < 200 && response.status >= 300) {
          const responseBody = await response.json();
          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 { nextcloudTalkHost } = await clientCredentials;
    const { json } = await auth.request({
      url: `${nextcloudTalkHost}/${endpoint}`,
      options: {
        method: "GET",
        ...options,
        headers: {
          ...options?.headers
        }
      }
    });
    return json;
  };
  return {
    getAvailability: () => {
      return Promise.resolve([]);
    },
    createMeeting: async (eventData) => {
      const appKeys = await getAppKeysFromSlug.getAppKeysFromSlug(CalEventParser.config.slug);
      const meetingPattern = appKeys.nextcloudTalkPattern || "{uuid}";
      const hostUrl = appKeys.nextcloudTalkHost;
      const meetingID = meetingPattern.replaceAll("{uuid}", uuid.v4()).replaceAll("{Title}", eventData.title).replaceAll("{Event Type Title}", eventData.type).replaceAll("{Scheduler}", eventData.attendees.map((a) => a.name).join("-")).replaceAll("{Organizer}", eventData.organizer.name).replaceAll("{Location}", eventData.location || "").replaceAll("{Team}", eventData.team?.name || "").replaceAll(" ", "-");
      try {
        const response = await fetchNextcloudApi(`ocs/v2.php/apps/spreed/api/v4/room`, {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            "OCS-APIRequest": "true"
          },
          body: JSON.stringify({
            roomType: 3,
            roomName: `${meetingID}`
          })
        });
        const result = nextcloudEventResultSchema.parse(response);
        if (result.ocs && result.ocs.data) {
          return {
            type: CalEventParser.config.type,
            id: result.ocs.data.token,
            password: "",
            url: `${hostUrl}/call/${result.ocs.data.token}`
          };
        }
        throw new Error(`Failed to create meeting. Response is ${JSON.stringify(result)}`);
      } catch (err) {
        console.error(err);
        throw new Error("Unexpected error");
      }
    },
    deleteMeeting: async (uid) => {
      try {
        const response = await fetchNextcloudApi(`ocs/v2.php/apps/spreed/api/v4/room/${uid}`, {
          method: "DELETE",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            "OCS-APIRequest": "true"
          }
        });
        const result = nextcloudEventResultSchema.parse(response);
        if (result.ocs && result.ocs.meta && result.ocs.meta.status === "ok") {
          return Promise.resolve();
        }
        throw new Error(`Failed to delete meeting. Response is ${JSON.stringify(result)}`);
      } catch (err) {
        return Promise.reject(new Error("Failed to delete meeting"));
      }
    },
    updateMeeting: (bookingRef) => {
      return Promise.resolve({
        type: CalEventParser.config.type,
        id: bookingRef.meetingId,
        password: bookingRef.meetingPassword,
        url: bookingRef.meetingUrl
      });
    }
  };
};
exports.default = NextcloudTalkVideoApiAdapter;
