import { defineEventHandler, createError } from 'h3'
import type LogtoClient from '@logto/node'

export default defineEventHandler(async (event) => {
  const client = event.context.logtoClient as LogtoClient | undefined
  const user = event.context.logtoUser

  if (!client) {
    return {
      authenticated: false,
      user: null,
      idToken: null,
      refreshToken: null
    }
  }

  let idToken = null
  let refreshToken = null

  try {
    idToken = await client.getIdToken()
  }
  catch {
    // Ignore
  }

  try {
    refreshToken = await client.getRefreshToken()
  }
  catch {
    // Ignore
  }

  return {
    authenticated: true,
    user,
    idToken,
    refreshToken: refreshToken ? `${refreshToken.substring(0, 20)}...` : null
  }
})
