import type { H3Event } from 'h3'

// Forward a request to platform-api's public scheduling API, preserving upstream
// status codes + messages so the client sees a real 404/409/503 instead of a
// generic 500. The internal API hostname never reaches the browser.
export async function forward(
  _event: H3Event,
  method: 'GET' | 'POST',
  path: string,
  opts: { query?: Record<string, any>; body?: any } = {},
): Promise<any> {
  const base = useRuntimeConfig().platformApiUrl
  try {
    return await $fetch(base + path, { method, query: opts.query, body: opts.body })
  } 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) })
  }
}

// Encode a single path segment safely.
export const seg = (s: string) => encodeURIComponent(s)
