import { defineEventHandler } from 'h3'
import { useStorage } from '#imports'
import { getUserSessionId } from 'nuxt-oidc-auth/runtime/server/utils/session.js'
import { decryptToken } from 'nuxt-oidc-auth/runtime/server/utils/security.js'

export default defineEventHandler(async (event) => {
  const sessionId = await getUserSessionId(event)
  const persistentSession = await useStorage('oidc').getItem(sessionId)

  let refreshToken = null
  if (persistentSession?.refreshToken) {
    const tokenKey = process.env.NUXT_OIDC_TOKEN_KEY!
    refreshToken = await decryptToken(persistentSession.refreshToken, tokenKey)
  }

  return {
    sessionId,
    persistentSession,
    refreshToken
  }
})
