import { LRUCache } from "lru-cache";
import { getToken } from "next-auth/jwt";
import { l as logger, a as safeStringify, p as prisma, L as LicenseKeySingleton, D as DeploymentRepository } from "./i18n-VAwx2uzJ.js";
import { g as getUserAvatarUrl } from "./event-types.js";
import { U as UserRepository } from "./user-LXWvjZHg.js";
const log = logger.getSubLogger({ prefix: ["getServerSession"] });
const CACHE = new LRUCache({ max: 1e3 });
async function getServerSession(options) {
  const { req, authOptions: { secret } = {} } = options;
  const token = await getToken({
    req,
    secret
  });
  log.debug("Getting server session", 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", safeStringify(cachedSession));
    return cachedSession;
  }
  const email = token.email.toLowerCase();
  const userFromDb = await prisma.user.findUnique({
    where: { email }
  });
  if (!userFromDb) {
    log.debug("No user found");
    return null;
  }
  const deploymentRepo = new DeploymentRepository(prisma);
  const licenseKeyService = await 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 UserRepository(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: 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 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", safeStringify(session));
  return session;
}
export {
  getServerSession
};
