"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const installation = require("./installation-aMIHG4H9.cjs");
const getServerSession = require("./getServerSession-R7W0aXpm.cjs");
const httpError = require("./http-error-mkY8Ke7V.cjs");
const getAppKeysFromSlug = require("./getAppKeysFromSlug-92RHW5nt.cjs");
const config = require("./config-HnxlgFgd.cjs");
const getSafeRedirectUrl = require("./getSafeRedirectUrl-M2YRxa9p.cjs");
const getInstalledAppPath = require("./getInstalledAppPath-oSgU9RsM.cjs");
const decodeOAuthState = require("./decodeOAuthState--7fljpCf.cjs");
const CrmService = require("./CrmService-p5JjmaGR.cjs");
async function handler$1(req, res) {
  if (req.method !== "GET")
    return res.status(405).json({ message: "Method not allowed" });
  const appKeys = await getAppKeysFromSlug.getAppKeysFromSlug(config.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.getServerSession({ req });
  const { teamId } = req.query;
  const user = req.session?.user;
  if (!user) {
    throw new httpError.HttpError({ statusCode: 401, message: "You must be logged in to do this" });
  }
  const userId = user.id;
  await installation.createDefaultInstallation({
    appType: `${config.appConfig.slug}_other_calendar`,
    user,
    slug: config.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.decodeOAuthState(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;
