import axios from "axios";
import { m as WEBAPP_URL } from "./index-Cw1zbw54.js";
import { g as getAppKeysFromSlug } from "./getAppKeysFromSlug-S62aYXii.js";
import { e as encodeOAuthState } from "./encodeOAuthState-ADe35aHB.js";
import { a as appConfig } from "./config-njEkgpNB.js";
import qs from "qs";
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 BiginCrmService from "./CrmService-4HMvtX1F.js";
async function handler$1(req, res) {
  if (req.method === "GET") {
    const appKeys = await getAppKeysFromSlug(appConfig.slug);
    const clientId = typeof appKeys.client_id === "string" ? appKeys.client_id : "";
    if (!clientId)
      return res.status(400).json({ message: "Zoho Bigin client_id missing." });
    const redirectUri = `${WEBAPP_URL}/api/integrations/zoho-bigin/callback`;
    const authUrl = axios.getUri({
      url: "https://accounts.zoho.com/oauth/v2/auth",
      params: {
        scope: appConfig.scope,
        client_id: clientId,
        response_type: "code",
        redirect_uri: redirectUri,
        access_type: "offline",
        state: encodeOAuthState(req)
      }
    });
    res.status(200).json({ url: authUrl });
    return;
  }
  res.status(400).json({ message: "Invalid request method." });
}
function isAuthorizedAccountsServerUrl(accountsServer) {
  const authorizedAccountServers = [
    "https://accounts.zoho.com",
    "https://accounts.zoho.eu",
    "https://accounts.zoho.in",
    "https://accounts.zoho.com.cn",
    "https://accounts.zoho.jp",
    "https://accounts.zohocloud.ca",
    "https://accounts.zoho.com.au"
  ];
  return authorizedAccountServers.includes(accountsServer);
}
async function handler(req, res) {
  const { code, "accounts-server": accountsServer } = req.query;
  const state = decodeOAuthState(req);
  if (code && typeof code !== "string") {
    res.status(400).json({ message: "`code` must be a string" });
    return;
  }
  if (!accountsServer || typeof accountsServer !== "string") {
    res.status(400).json({ message: "`accounts-server` is required and must be a string" });
    return;
  }
  if (!isAuthorizedAccountsServerUrl(accountsServer)) {
    res.status(400).json({ message: "`accounts-server` is not authorized" });
    return;
  }
  if (!req.session?.user?.id) {
    res.status(401).json({ message: "You must be logged in to do this" });
    return;
  }
  const appKeys = await getAppKeysFromSlug(appConfig.slug);
  const clientId = typeof appKeys.client_id === "string" ? appKeys.client_id : "";
  const clientSecret = typeof appKeys.client_secret === "string" ? appKeys.client_secret : "";
  if (!clientId)
    return res.status(400).json({ message: "Zoho Bigin client_id missing." });
  if (!clientSecret)
    return res.status(400).json({ message: "Zoho Bigin client_secret missing." });
  const accountsUrl = `${accountsServer}/oauth/v2/token`;
  const redirectUri = `${WEBAPP_URL}/api/integrations/${appConfig.slug}/callback`;
  const formData = {
    client_id: clientId,
    client_secret: clientSecret,
    code,
    redirect_uri: redirectUri,
    grant_type: "authorization_code"
  };
  const tokenInfo = await axios.post(accountsUrl, qs.stringify(formData), {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    }
  });
  tokenInfo.data.expiryDate = Math.round(Date.now() + tokenInfo.data.expires_in);
  tokenInfo.data.accountServer = accountsServer;
  await createOAuthAppCredential({ appId: appConfig.slug, type: appConfig.type }, tokenInfo.data, req);
  res.redirect(
    getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath({ variant: appConfig.variant, slug: appConfig.slug })
  );
}
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add: handler$1,
  callback: handler
}, Symbol.toStringTag, { value: "Module" }));
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  CrmService: BiginCrmService
}, Symbol.toStringTag, { value: "Module" }));
export {
  index$1 as api,
  index as lib
};
