"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const lruCache = require("lru-cache");
const jwt = require("next-auth/jwt");
const index = require("./user-v6mfWQ2d.cjs");
const getAvatarUrl = require("./getAvatarUrl-Ea0npYkA.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", index.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", index.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 index.UserRepository(index.prisma);
  const user = 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.id,
      name: user.name,
      username: user.username,
      email: user.email,
      emailVerified: user.emailVerified,
      email_verified: user.emailVerified !== null,
      completedOnboarding: user.completedOnboarding,
      role: user.role,
      image: getAvatarUrl.getUserAvatarUrl({
        avatarUrl: user.avatarUrl
      }),
      belongsToActiveTeam: token.belongsToActiveTeam,
      org: token.org,
      orgAwareUsername: token.orgAwareUsername,
      locale: user.locale ?? void 0,
      profile: user.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", index.safeStringify(session));
  return session;
}
exports.getServerSession = getServerSession;
