// Dev/scaffolding: proxies POST /tenants to platform-api with the logged-in
// user's access token. Lets you create a tenant from the browser without
// minting tokens by hand. Will be replaced by a real "create workspace" flow
// with proper UI later.

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' })
  }

  const body = await readBody(event)
  const base = process.env.PLATFORM_API_INTERNAL_URL ?? 'http://platform-api:3001'

  return $fetch(`${base}/tenants`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${accessToken}` },
    body,
  })
})
