/**
 * CRA API proxy — catch-all. Proxies /api/v1/cra/* to the Python backend
 * (e.g. POST /api/v1/cra/assess, the standalone CRA risk-assessment endpoint).
 */
import { NextRequest, NextResponse } from 'next/server'

const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:8000'

async function forward(request: NextRequest, path: string[], method: 'GET' | 'POST') {
  const pathStr = path.join('/')
  const search = request.nextUrl.searchParams.toString()
  const url = `${BACKEND_URL}/api/v1/cra/${pathStr}${search ? `?${search}` : ''}`

  const init: RequestInit = {
    method,
    headers: { 'Content-Type': 'application/json' },
    signal: AbortSignal.timeout(30000),
  }
  if (method === 'POST') {
    try {
      init.body = JSON.stringify(await request.json())
    } catch {
      init.body = '{}'
    }
  }

  try {
    const response = await fetch(url, init)
    const text = await response.text()
    if (!response.ok) {
      return NextResponse.json(
        { error: `Backend Error: ${response.status}`, details: text },
        { status: response.status },
      )
    }
    return new NextResponse(text, {
      status: response.status,
      headers: { 'Content-Type': 'application/json' },
    })
  } catch (error) {
    console.error('CRA API proxy error:', error)
    return NextResponse.json({ error: 'Verbindung zum Backend fehlgeschlagen' }, { status: 503 })
  }
}

export async function GET(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) {
  const { path } = await params
  return forward(request, path, 'GET')
}

export async function POST(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) {
  const { path } = await params
  return forward(request, path, 'POST')
}
