"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const defaultHandler = require("./defaultHandler-MSjhitc-.cjs");
const index$2 = require("./orgDomains-W_rFTMBa.cjs");
const getSafeRedirectUrl = require("./getSafeRedirectUrl-M2YRxa9p.cjs");
const httpError = require("./http-error-mkY8Ke7V.cjs");
const defaultResponder = require("./defaultResponder-pIXL4EeF.cjs");
const getAppKeysFromSlug = require("./getAppKeysFromSlug-92RHW5nt.cjs");
const getInstalledAppPath = require("./getInstalledAppPath-oSgU9RsM.cjs");
const decodeOAuthState = require("./decodeOAuthState--7fljpCf.cjs");
const config = require("./config-mpxgmOtk.cjs");
const CrmService = require("./CrmService-RbHEBxpX.cjs");
const add = defaultHandler.defaultHandler({
  GET: Promise.resolve().then(() => require("./_getAdd-gOidhU11.cjs"))
});
async function getHandler(req, res) {
  const { code } = req.query;
  const state = decodeOAuthState.decodeOAuthState(req);
  const redirectAfterSuccess = getSafeRedirectUrl.getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath.getInstalledAppPath({ variant: config.appConfig.variant, slug: config.appConfig.slug });
  const redirectAfterSuccessOrError = getSafeRedirectUrl.getSafeRedirectUrl(state?.onErrorReturnTo) ?? redirectAfterSuccess;
  if (!code || typeof code !== "string") {
    if (state?.onErrorReturnTo || state?.returnTo) {
      res.redirect(redirectAfterSuccessOrError);
      return;
    }
    throw new httpError.HttpError({ statusCode: 400, message: "`code` must be a string" });
  }
  if (!req.session?.user?.id) {
    throw new httpError.HttpError({ statusCode: 401, message: "You must be logged in to do this" });
  }
  const { client_id, client_secret } = await getAppKeysFromSlug.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: `${index$2.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 index$2.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.defaultHandler({
  GET: Promise.resolve({ default: defaultResponder.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: CrmService.default
}, Symbol.toStringTag, { value: "Module" }));
exports.api = index$1;
exports.lib = index;
