"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const defaultHandler = require("./defaultHandler-MSjhitc-.cjs");
const axios = require("axios");
const qs = require("qs");
const index$2 = require("./orgDomains-W_rFTMBa.cjs");
const getSafeRedirectUrl = require("./getSafeRedirectUrl-M2YRxa9p.cjs");
const getAppKeysFromSlug = require("./getAppKeysFromSlug-92RHW5nt.cjs");
const getInstalledAppPath = require("./getInstalledAppPath-oSgU9RsM.cjs");
const createOAuthAppCredential = require("./createOAuthAppCredential-aX4ofvTS.cjs");
const decodeOAuthState = require("./decodeOAuthState--7fljpCf.cjs");
const config = require("./config-ueGuNuh0.cjs");
const CrmService = require("./CrmService-1G_lYNoJ.cjs");
const add = defaultHandler.defaultHandler({
  GET: Promise.resolve().then(() => require("./_getAdd-EnwDv0vO.cjs"))
});
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.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 = `${index$2.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.createOAuthAppCredential({ appId: config.appConfig.slug, type: config.appConfig.type }, zohoCrmTokenInfo.data, req);
  const state = decodeOAuthState.decodeOAuthState(req);
  res.redirect(
    getSafeRedirectUrl.getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath.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: CrmService.default
}, Symbol.toStringTag, { value: "Module" }));
exports.api = index$1;
exports.lib = index;
