import { d as defaultHandler } from "./defaultHandler-yvm7aMmf.js";
import axios from "axios";
import qs from "qs";
import { m as WEBAPP_URL } from "./index-Cw1zbw54.js";
import { g as getSafeRedirectUrl } from "./getSafeRedirectUrl-hxmyPhEi.js";
import { g as getAppKeysFromSlug } from "./getAppKeysFromSlug-S62aYXii.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 { a as appConfig } from "./config-_JGd9bC0.js";
import ZohoCrmCrmService from "./CrmService--RHu1ZdP.js";
const add = defaultHandler({
  GET: import("./_getAdd-UG9eNHz0.js")
});
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;
  if (code === void 0 && 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) {
    return res.status(401).json({ message: "You must be logged in to do this" });
  }
  let clientId = "";
  let clientSecret = "";
  const appKeys = await getAppKeysFromSlug("zohocrm");
  if (typeof appKeys.client_id === "string")
    clientId = appKeys.client_id;
  if (typeof appKeys.client_secret === "string")
    clientSecret = appKeys.client_secret;
  if (!clientId)
    return res.status(400).json({ message: "Zoho Crm consumer key missing." });
  if (!clientSecret)
    return res.status(400).json({ message: "Zoho Crm consumer secret missing." });
  const url = `${accountsServer}/oauth/v2/token`;
  const redirectUri = `${WEBAPP_URL}/api/integrations/zohocrm/callback`;
  const formData = {
    grant_type: "authorization_code",
    client_id: clientId,
    client_secret: clientSecret,
    redirect_uri: redirectUri,
    code
  };
  const zohoCrmTokenInfo = await axios({
    method: "post",
    url,
    data: qs.stringify(formData),
    headers: {
      "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    }
  });
  zohoCrmTokenInfo.data.expiryDate = Math.round(Date.now() + 60 * 60);
  zohoCrmTokenInfo.data.accountServer = accountsServer;
  await createOAuthAppCredential({ appId: appConfig.slug, type: appConfig.type }, zohoCrmTokenInfo.data, req);
  const state = decodeOAuthState(req);
  res.redirect(
    getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath({ variant: "other", slug: "zohocrm" })
  );
}
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add,
  callback: handler
}, Symbol.toStringTag, { value: "Module" }));
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  CrmService: ZohoCrmCrmService
}, Symbol.toStringTag, { value: "Module" }));
export {
  index$1 as api,
  index as lib
};
