// Scaffolding route: pulls the signed-in user's profile + tenants + subscriptions
// from platform-api, using the user's Authentik access token forwarded from the
// encrypted server-side session.
//
// Verifies the full chain: portal session → access token → platform-api JWT guard → Mongo.

import { getUserSession } from 'nuxt-oidc-auth/runtime/server/utils/session.js'

export default defineEventHandler(async (event) => {
  const session = await getUserSession(event).catch(() => null)
  const accessToken = (session as { accessToken?: string } | null)?.accessToken

  if (!accessToken) {
    throw createError({ statusCode: 401, statusMessage: 'Not signed in or no access token' })
  }

  const base = process.env.PLATFORM_API_INTERNAL_URL ?? 'http://platform-api:3001'
  const headers = { Authorization: `Bearer ${accessToken}` }

  const [profile, tenants, subscriptions] = await Promise.all([
    $fetch(`${base}/users/me`, { headers }),
    $fetch(`${base}/tenants`, { headers }),
    $fetch(`${base}/subscriptions`, { headers }),
  ])

  return { profile, tenants, subscriptions }
})
