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

const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'

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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ derived_id: string }> }
) {
  const { derived_id } = await params
  try {
    const resp = await fetch(
      `${BACKEND_URL}/api/v1/quaidal/controls/${encodeURIComponent(derived_id)}`,
      { headers: { 'X-Tenant-ID': tenantHeader(request) }, cache: 'no-store' }
    )
    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 })
  }
}
