import { stringify } from "querystring";
import { v4 } from "uuid";
import { z } from "zod";
import { l as logger, a as safeStringify, p as prisma } from "./i18n-tiaWqB1b.js";
import { g as getAppKeysFromSlug } from "./getAppKeysFromSlug-JDbO8QtR.js";
import { g as getParsedAppKeysFromSlug } from "./getParsedAppKeysFromSlug-QgCsBSun.js";
import { O as OAuthManager, i as invalidateCredential, m as markTokenAsExpired } from "./markTokenAsExpired-_H5_o27U.js";
import { o as oAuthManagerHelper } from "./oAuthManagerHelper-_7BHiUIP.js";
import { c as config } from "./CalEventParser-tm9lJVKT.js";
import { a as appKeysSchema } from "./zod-I9cQMjNL.js";
const nextcloudEventResultSchema = z.object({
  ocs: z.object({
    meta: z.object({
      status: z.string(),
      statuscode: z.number(),
      message: z.string()
    }),
    data: z.object({
      token: z.string()
    })
  })
});
const NextcloudTalkVideoApiAdapter = (credential) => {
  const tokenResponse = oAuthManagerHelper.getTokenObjectFromCredential(credential);
  const clientCredentials = getParsedAppKeysFromSlug(config.slug, appKeysSchema);
  const fetchNextcloudApi = async (endpoint, options) => {
    const auth = new OAuthManager({
      credentialSyncVariables: oAuthManagerHelper.credentialSyncVariables,
      resourceOwner: {
        type: "user",
        id: credential.userId
      },
      appSlug: 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 = 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 = logger.getSubLogger({ prefix: ["nextcloudtalkvideo:isTokenObjectUnusable"] });
        myLog.debug(safeStringify({ status: response.status, ok: response.ok }));
        if (!response.ok || response.status < 200 && response.status >= 300) {
          const responseBody = await response.json();
          myLog.debug(safeStringify({ responseBody }));
          if (responseBody.error === "invalid_grant") {
            return { reason: responseBody.error };
          }
        }
        return null;
      },
      isAccessTokenUnusable: async function(response) {
        const myLog = logger.getSubLogger({ prefix: ["nextcloudtalkvideo:isAccessTokenUnusable"] });
        myLog.debug(safeStringify({ status: response.status, ok: response.ok }));
        if (!response.ok || response.status < 200 && response.status >= 300) {
          const responseBody = await response.json();
          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: {
            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(config.slug);
      const meetingPattern = appKeys.nextcloudTalkPattern || "{uuid}";
      const hostUrl = appKeys.nextcloudTalkHost;
      const meetingID = meetingPattern.replaceAll("{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: 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: config.type,
        id: bookingRef.meetingId,
        password: bookingRef.meetingPassword,
        url: bookingRef.meetingUrl
      });
    }
  };
};
export {
  NextcloudTalkVideoApiAdapter as default
};
