// Temporary proxy used only to verify O.2's audience-gating from the browser.
// This forwards the customer-portal session's access token — which has aud
// 'dezky-portal' — to platform-api's POST /partners. We expect 403 because
// that endpoint requires aud='dezky-operator'. Delete this file once the
// operator portal exists and the real (positive) test runs from there.

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'
  try {
    return await $fetch(`${base}/partners`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${accessToken}` },
      body,
    })
  } catch (err: unknown) {
    const e = err as { statusCode?: number; data?: unknown }
    throw createError({ statusCode: e.statusCode ?? 500, data: e.data })
  }
})
