import type { H3Event } from 'h3'
import { joinURL } from 'ufo'
import { jwtDecode } from 'jwt-decode'

export default defineEventHandler(async (event: H3Event) => {
  const { serverApiBaseUrl, clientProxyBasePath } = useRuntimeConfig().public
  const escapedClientProxyBasePath = clientProxyBasePath.replace(/^\//, '\\/')
  // Use the escaped value in the regex
  const path = event.path.replace(new RegExp(`^${escapedClientProxyBasePath}`), '')
  const target = joinURL(serverApiBaseUrl, path)

  const session = await getUserSession(event)
  const accessToken = session?.jwt?.accessToken

  if (!accessToken && event.path !== '/api/actuator/health') {
    throw createError({
      statusCode: 401,
      statusMessage: 'Not authenticated'
    })
  }

  if (accessToken) console.log('🔀 [PROXY] Expiration:', new Date(jwtDecode(accessToken).exp! * 1000).toISOString())
  console.log('🔀 [PROXY] Proxying request to:', target)

  return proxyRequest(event, target, {
    headers: {
      Authorization: `Bearer ${accessToken}`
    }
  })
})
