import { NextRequest, NextResponse } from 'next/server'

// Proxy for the CRA Art. 14 incident-reporting (Meldewesen) endpoints.
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'

function tenant(request: NextRequest): string {
  return request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}

async function forward(request: NextRequest, path: string[], method: string) {
  const sub = path.join('/')
  const { searchParams } = new URL(request.url)
  const qs = searchParams.toString()
  const url = `${BACKEND_URL}/api/v1/cra/incidents${sub ? `/${sub}` : ''}${qs ? `?${qs}` : ''}`
  const init: RequestInit = {
    method,
    headers: { 'X-Tenant-ID': tenant(request), 'Content-Type': 'application/json' },
  }
  if (method !== 'GET') init.body = await request.text()
  try {
    const resp = await fetch(url, init)
    const body = await resp.text()
    return new NextResponse(body, {
      status: resp.status,
      headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
    })
  } catch (err) {
    return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
  }
}

export async function GET(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  return forward(request, (await params).path || [], 'GET')
}
export async function POST(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  return forward(request, (await params).path || [], 'POST')
}
export async function PATCH(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  return forward(request, (await params).path || [], 'PATCH')
}
