import { d as defaultHandler } from "./defaultHandler-yvm7aMmf.js";
import { z as WEBAPP_URL, p as prisma } from "./orgDomains-eTg-cjth.js";
import { g as getSafeRedirectUrl } from "./getSafeRedirectUrl-3UmuXRrS.js";
import { H as HttpError } from "./http-error-RJXCPZV2.js";
import { d as defaultResponder } from "./defaultResponder-0QFUGn0p.js";
import { g as getAppKeysFromSlug } from "./getAppKeysFromSlug-CJxDAalk.js";
import { g as getInstalledAppPath } from "./getInstalledAppPath-vg9hE5pP.js";
import { d as decodeOAuthState } from "./decodeOAuthState-KhwGAxqw.js";
import { a as appConfig } from "./config-eqo80879.js";
import CloseComCRMService from "./CrmService-kY3S2DqP.js";
const add = defaultHandler({
  GET: import("./_getAdd-fgaXv_YT.js")
});
async function getHandler(req, res) {
  const { code } = req.query;
  const state = decodeOAuthState(req);
  const redirectAfterSuccess = getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath({ variant: appConfig.variant, slug: appConfig.slug });
  const redirectAfterSuccessOrError = getSafeRedirectUrl(state?.onErrorReturnTo) ?? redirectAfterSuccess;
  if (!code || typeof code !== "string") {
    if (state?.onErrorReturnTo || state?.returnTo) {
      res.redirect(redirectAfterSuccessOrError);
      return;
    }
    throw new HttpError({ statusCode: 400, message: "`code` must be a string" });
  }
  if (!req.session?.user?.id) {
    throw new HttpError({ statusCode: 401, message: "You must be logged in to do this" });
  }
  const { client_id, client_secret } = await getAppKeysFromSlug("closecom");
  if (!client_id || typeof client_id !== "string")
    return res.status(400).json({ message: "Close.com client_id missing." });
  if (!client_secret || typeof client_secret !== "string")
    return res.status(400).json({ message: "Close.com client_secret missing." });
  try {
    const response = await fetch("https://api.close.com/oauth2/token/", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: new URLSearchParams({
        client_id,
        client_secret,
        grant_type: "authorization_code",
        code,
        redirect_uri: `${WEBAPP_URL}/api/integrations/closecom/callback`
      })
    });
    if (!response.ok) {
      throw new Error("Failed to get access token");
    }
    const responseJson = await response.json();
    const { access_token, refresh_token, expires_in } = responseJson;
    const expires_at = Date.now() + expires_in * 1e3;
    await prisma.credential.create({
      data: {
        type: "closecom_crm",
        key: {
          access_token,
          refresh_token,
          expires_at
        },
        userId: req.session.user.id,
        appId: "closecom"
      }
    });
    return res.redirect(redirectAfterSuccess);
  } catch (error) {
    console.error("Error getting close.com access token", error);
    return res.redirect(`${redirectAfterSuccessOrError}?error=Error getting close.com access token`);
  }
}
const callback = defaultHandler({
  GET: Promise.resolve({ default: defaultResponder(getHandler) })
});
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add,
  callback
}, Symbol.toStringTag, { value: "Module" }));
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  CrmService: CloseComCRMService
}, Symbol.toStringTag, { value: "Module" }));
export {
  index$1 as api,
  index as lib
};
