export const dynamic = 'force-dynamic'

function jsonResponse(body: unknown, status: number) {
  return new Response(JSON.stringify(body), {
    status,
    headers: {
      'content-type': 'application/json; charset=utf-8',
      'cache-control': 'no-store',
    },
  })
}

export async function GET() {
  const backendBase = (process.env.BACKEND_URL || 'http://127.0.0.1:8000').replace(/\/$/, '')
  const url = `${backendBase}/health`

  try {
    const res = await fetch(url, { cache: 'no-store' })
    const text = await res.text()
    let backend: unknown = text
    try {
      backend = JSON.parse(text)
    } catch {
      // keep text
    }

    if (!res.ok) {
      return jsonResponse(
        {
          status: 'degraded',
          frontend: { ok: true },
          backend: { ok: false, status: res.status, body: backend },
        },
        503
      )
    }

    return jsonResponse(
      {
        status: 'ok',
        frontend: { ok: true },
        backend: { ok: true, body: backend },
      },
      200
    )
  } catch (err) {
    return jsonResponse(
      {
        status: 'down',
        frontend: { ok: true },
        backend: { ok: false, error: err instanceof Error ? err.message : String(err) },
      },
      503
    )
  }
}

