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

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

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

export async function GET(request: NextRequest, ctx: { params: Promise<{ docId: string }> }) {
  const { docId } = await ctx.params
  try {
    const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/documents/${docId}`, {
      headers: { 'X-Tenant-ID': tenant(request) },
    })
    const text = await resp.text()
    return new NextResponse(text, {
      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 })
  }
}
