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'
}

/** GET /sbom -> List uploads. We map this to the backend /sboms endpoint. */
export async function GET(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  const { id } = await ctx.params
  try {
    const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/sboms`, {
      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 })
  }
}

/** POST /sbom -> multipart upload to backend /sbom/upload */
export async function POST(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  const { id } = await ctx.params
  try {
    const formData = await request.formData()
    const upstreamForm = new FormData()
    for (const [key, value] of formData.entries()) {
      upstreamForm.append(key, value)
    }
    const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/sbom/upload`, {
      method: 'POST',
      headers: { 'X-Tenant-ID': tenant(request) },
      body: upstreamForm as unknown as BodyInit,
    })
    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 })
  }
}
