import { a as createDefaultInstallation } from "./installation-A6q4n0tL.js";
import { getServerSession } from "./getServerSession-ZkQhIqnA.js";
import { H as HttpError } from "./http-error-RJXCPZV2.js";
import { g as getAppKeysFromSlug } from "./getAppKeysFromSlug-IDaQR-Xd.js";
import { a as appConfig } from "./config-Tx3nDP-1.js";
import { g as getSafeRedirectUrl } from "./getSafeRedirectUrl-VGWYovUy.js";
import { g as getInstalledAppPath } from "./getInstalledAppPath-d831DYzR.js";
import { d as decodeOAuthState } from "./decodeOAuthState-KhwGAxqw.js";
import PipedriveCrmService from "./CrmService-qTR017nB.js";
async function handler$1(req, res) {
  if (req.method !== "GET")
    return res.status(405).json({ message: "Method not allowed" });
  const appKeys = await getAppKeysFromSlug(appConfig.slug);
  let client_id = "";
  if (typeof appKeys.client_id === "string")
    client_id = appKeys.client_id;
  if (!client_id)
    return res.status(400).json({ message: "pipedrive client id missing." });
  req.session = await getServerSession({ req });
  const { teamId } = req.query;
  const user = req.session?.user;
  if (!user) {
    throw new HttpError({ statusCode: 401, message: "You must be logged in to do this" });
  }
  const userId = user.id;
  await createDefaultInstallation({
    appType: `${appConfig.slug}_other_calendar`,
    user,
    slug: appConfig.slug,
    key: {},
    teamId: Number(teamId)
  });
  const tenantId = teamId ? teamId : userId;
  res.status(200).json({
    url: `https://oauth.pipedrive.com/oauth/authorize?client_id=${appKeys.client_id}&redirect_uri=https://app.revert.dev/oauth-callback/pipedrive&state={%22tenantId%22:%22${tenantId}%22,%22revertPublicToken%22:%22${process.env.REVERT_PUBLIC_TOKEN}%22}`,
    newTab: true
  });
}
async function handler(req, res) {
  if (!req.session?.user?.id) {
    return res.status(401).json({ message: "You must be logged in to do this" });
  }
  const state = decodeOAuthState(req);
  res.redirect(
    getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath({ variant: appConfig.variant, slug: 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: PipedriveCrmService
}, Symbol.toStringTag, { value: "Module" }));
export {
  index$1 as api,
  index as lib
};
