// Catch-all proxy for the dezky Scheduling admin API. Forwards any method under
// /api/tenants/:slug/scheduling/** to platform-api's
// /api/v1/tenants/:slug/scheduling/** with the signed-in user's access token;
// platform-api enforces tenant membership. Upstream status codes are preserved
// so the admin UI sees real 400/403/404/409 responses.

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 slug = getRouterParam(event, 'slug')
  const path = getRouterParam(event, 'path') ?? ''
  const base = process.env.PLATFORM_API_INTERNAL_URL ?? 'http://platform-api:3001'
  const method = event.method
  const query = getQuery(event)
  const body = ['POST', 'PUT', 'PATCH'].includes(method) ? await readBody(event).catch(() => undefined) : undefined

  try {
    return await $fetch(`${base}/api/v1/tenants/${slug}/scheduling/${path}`, {
      method: method as any,
      query,
      body,
      headers: { Authorization: `Bearer ${accessToken}` },
    })
  } catch (err: any) {
    const status = err?.response?.status ?? 502
    const raw = err?.data?.message ?? err?.response?._data?.message ?? 'Upstream error'
    throw createError({ statusCode: status, statusMessage: Array.isArray(raw) ? raw.join(', ') : String(raw) })
  }
})
