// Smoke test: forwards the operator's access token to platform-api's POST
// /partners. If the operator OAuth setup is correct, this returns 200 with
// the created (or already-existing) partner. Idempotent — Partner is
// soft-terminated, never hard-deleted, so re-running with the same slug
// returns 409 Conflict (also a success signal for the audience guard).

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 base = process.env.PLATFORM_API_INTERNAL_URL ?? 'http://platform-api:3001'
  try {
    return await $fetch(`${base}/partners`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${accessToken}` },
      body: {
        slug: 'test-partner',
        name: 'Smoke Test Partner',
        domain: 'test-partner.example',
        status: 'in-negotiation',
        marginPct: 20,
      },
    })
  } catch (err: unknown) {
    const e = err as { statusCode?: number; data?: unknown }
    throw createError({ statusCode: e.statusCode ?? 500, data: e.data })
  }
})
