"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const axios = require("axios");
const index$2 = require("./index-QSf6WJj0.cjs");
const getAppKeysFromSlug = require("./getAppKeysFromSlug-duun9y1Q.cjs");
const encodeOAuthState = require("./encodeOAuthState-VBfelnxQ.cjs");
const config = require("./config-4nZw2972.cjs");
const qs = require("qs");
const getSafeRedirectUrl = require("./getSafeRedirectUrl-MkOChEjJ.cjs");
const getInstalledAppPath = require("./getInstalledAppPath-2GQAo7UC.cjs");
const createOAuthAppCredential = require("./createOAuthAppCredential--aER13Ig.cjs");
const decodeOAuthState = require("./decodeOAuthState--7fljpCf.cjs");
const CrmService = require("./CrmService-zkKbvPc2.cjs");
async function handler$1(req, res) {
  if (req.method === "GET") {
    const appKeys = await getAppKeysFromSlug.getAppKeysFromSlug(config.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 = `${index$2.WEBAPP_URL}/api/integrations/zoho-bigin/callback`;
    const authUrl = axios.getUri({
      url: "https://accounts.zoho.com/oauth/v2/auth",
      params: {
        scope: config.appConfig.scope,
        client_id: clientId,
        response_type: "code",
        redirect_uri: redirectUri,
        access_type: "offline",
        state: encodeOAuthState.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.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.getAppKeysFromSlug(config.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 = `${index$2.WEBAPP_URL}/api/integrations/${config.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.createOAuthAppCredential({ appId: config.appConfig.slug, type: config.appConfig.type }, tokenInfo.data, req);
  res.redirect(
    getSafeRedirectUrl.getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath.getInstalledAppPath({ variant: config.appConfig.variant, slug: config.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: CrmService.default
}, Symbol.toStringTag, { value: "Module" }));
exports.api = index$1;
exports.lib = index;
