import { stringify } from "querystring";
import { m as WEBAPP_URL, p as prisma, l as logger } from "./index-Cw1zbw54.js";
import { d as defaultHandler } from "./defaultHandler-yvm7aMmf.js";
import { d as defaultResponder } from "./defaultResponder-s4VQhYfH.js";
import { g as getAppKeysFromSlug } from "./getAppKeysFromSlug-S62aYXii.js";
import { e as encodeOAuthState } from "./encodeOAuthState-ADe35aHB.js";
import { g as getSafeRedirectUrl } from "./getSafeRedirectUrl-hxmyPhEi.js";
import { g as getInstalledAppPath } from "./getInstalledAppPath-6P3H-VDB.js";
import { c as createOAuthAppCredential } from "./createOAuthAppCredential-UOwy2cXA.js";
import { d as decodeOAuthState } from "./decodeOAuthState-KhwGAxqw.js";
import { v4 } from "uuid";
import { z } from "zod";
import { C as appKeysSchema, a as safeStringify } from "./index-browser-c8sQ7p7S.js";
import { g as getParsedAppKeysFromSlug } from "./getParsedAppKeysFromSlug-MNhyH762.js";
import { O as OAuthManager, i as invalidateCredential, m as markTokenAsExpired } from "./markTokenAsExpired-x3_Cm7r4.js";
import { o as oAuthManagerHelper } from "./oAuthManagerHelper-6IQMBKDe.js";
import { aK as config } from "./email-manager-ED8hrFPG.js";
async function handler$1(req) {
  const user = req?.session?.user;
  if (!user) {
    return { status: 401, body: { error: "Unauthorized" } };
  }
  const appKeys = await getAppKeysFromSlug("nextcloudtalk");
  const hostUrl = appKeys.nextcloudTalkHost;
  const client_id = appKeys.nextcloudTalkClientId;
  const client_secret = appKeys.nextcloudTalkClientSecret;
  const state = encodeOAuthState(req);
  const params = {
    response_type: "code",
    client_id,
    client_secret,
    redirect_uri: `${WEBAPP_URL}/api/integrations/nextcloudtalk/callback`,
    state
  };
  const query = stringify(params);
  const url = `${hostUrl}/index.php/apps/oauth2/authorize?${query}`;
  return { url };
}
const add = defaultHandler({
  GET: Promise.resolve({ default: defaultResponder(handler$1) })
});
async function handler(req, res) {
  const state = decodeOAuthState(req);
  const userId = req.session?.user.id;
  if (!userId) {
    return res.status(404).json({ message: "No user found" });
  }
  const { code } = req.query;
  const appKeys = await getAppKeysFromSlug("nextcloudtalk");
  const hostUrl = appKeys.nextcloudTalkHost;
  const client_id = appKeys.nextcloudTalkClientId;
  const client_secret = appKeys.nextcloudTalkClientSecret;
  const result = await fetch(`${hostUrl}/index.php/apps/oauth2/api/v1/token`, {
    method: "POST",
    body: JSON.stringify({
      grant_type: "authorization_code",
      code,
      client_id,
      client_secret,
      redirect_uri: `${WEBAPP_URL}/api/integrations/nextcloudtalk/callback`
    }),
    headers: {
      "Content-Type": "application/json"
    }
  });
  if (result.status !== 200) {
    let errorMessage = "Something is wrong with the Nextcloud API";
    try {
      const responseBody2 = await result.json();
      errorMessage = responseBody2.error;
    } catch (e) {
    }
    res.status(400).json({ message: errorMessage });
    return;
  }
  const responseBody = await result.json();
  if (responseBody.error) {
    res.status(400).json({ message: responseBody.error });
    return;
  }
  await prisma.credential.deleteMany({
    where: {
      type: "nextcloudtalk_video",
      userId,
      appId: "nextcloudtalk"
    }
  });
  await createOAuthAppCredential({ appId: "nextcloudtalk", type: "nextcloudtalk_video" }, responseBody, req);
  res.redirect(
    getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath({ variant: "conferencing", slug: "nextcloudtalk" })
  );
}
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add,
  callback: handler
}, Symbol.toStringTag, { value: "Module" }));
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
      });
    }
  };
};
const NextcloudTalkVideoApiAdapter$1 = NextcloudTalkVideoApiAdapter;
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  VideoApiAdapter: NextcloudTalkVideoApiAdapter$1
}, Symbol.toStringTag, { value: "Module" }));
export {
  index$1 as api,
  index as lib
};
