"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const lruCache = require("lru-cache");
const jwt = require("next-auth/jwt");
const index = require("./index-QSf6WJj0.cjs");
const getAvatarUrl = require("./getAvatarUrl-F-7KLNrp.cjs");
const indexBrowser = require("./index-browser-RtwB1hqI.cjs");
const user = require("./user-d8lRSBlE.cjs");
const log = index.logger.getSubLogger({ prefix: ["getServerSession"] });
const CACHE = new lruCache.LRUCache({ max: 1e3 });
async function getServerSession(options) {
  const { req, authOptions: { secret } = {} } = options;
  const token = await jwt.getToken({
    req,
    secret
  });
  log.debug("Getting server session", indexBrowser.safeStringify({ token }));
  if (!token || !token.email || !token.sub) {
    log.debug("Couldn't get token");
    return null;
  }
  const cachedSession = CACHE.get(JSON.stringify(token));
  if (cachedSession) {
    log.debug("Returning cached session", indexBrowser.safeStringify(cachedSession));
    return cachedSession;
  }
  const email = token.email.toLowerCase();
  const userFromDb = await index.prisma.user.findUnique({
    where: { email }
  });
  if (!userFromDb) {
    log.debug("No user found");
    return null;
  }
  const deploymentRepo = new index.DeploymentRepository(index.prisma);
  const licenseKeyService = await index.LicenseKeySingleton.getInstance(deploymentRepo);
  const hasValidLicense = await licenseKeyService.checkLicense();
  let upId = token.upId;
  if (!upId) {
    upId = `usr-${userFromDb.id}`;
  }
  if (!upId) {
    log.error("No upId found for session", { userId: userFromDb.id });
    return null;
  }
  const userRepository = new user.UserRepository(index.prisma);
  const user$1 = await userRepository.enrichUserWithTheProfile({
    user: userFromDb,
    upId
  });
  const session = {
    hasValidLicense,
    expires: new Date(typeof token.exp === "number" ? token.exp * 1e3 : Date.now()).toISOString(),
    user: {
      id: user$1.id,
      name: user$1.name,
      username: user$1.username,
      email: user$1.email,
      emailVerified: user$1.emailVerified,
      email_verified: user$1.emailVerified !== null,
      completedOnboarding: user$1.completedOnboarding,
      role: user$1.role,
      image: getAvatarUrl.getUserAvatarUrl({
        avatarUrl: user$1.avatarUrl
      }),
      belongsToActiveTeam: token.belongsToActiveTeam,
      org: token.org,
      orgAwareUsername: token.orgAwareUsername,
      locale: user$1.locale ?? void 0,
      profile: user$1.profile
    },
    profileId: token.profileId,
    upId
  };
  if (token?.impersonatedBy?.id) {
    const impersonatedByUser = await index.prisma.user.findUnique({
      where: {
        id: token.impersonatedBy.id
      },
      select: {
        id: true,
        role: true
      }
    });
    if (impersonatedByUser) {
      session.user.impersonatedBy = {
        id: impersonatedByUser?.id,
        role: impersonatedByUser.role
      };
    }
  }
  CACHE.set(JSON.stringify(token), session);
  log.debug("Returned session", indexBrowser.safeStringify(session));
  return session;
}
exports.getServerSession = getServerSession;
