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

/** GET /api/sdk/v1/cra/projects -> Backend list */
export async function GET(request: NextRequest) {
  const tenantId = tenantHeader(request)
  const { searchParams } = new URL(request.url)
  const qs = searchParams.toString()
  try {
    const resp = await fetch(
      `${BACKEND_URL}/api/v1/cra/projects${qs ? `?${qs}` : ''}`,
      { headers: { 'X-Tenant-ID': tenantId } }
    )
    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 }
    )
  }
}

/** POST /api/sdk/v1/cra/projects -> Backend create */
export async function POST(request: NextRequest) {
  const tenantId = tenantHeader(request)
  const body = await request.text()
  try {
    const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects`, {
      method: 'POST',
      headers: {
        'X-Tenant-ID': tenantId,
        'Content-Type': 'application/json',
      },
      body,
    })
    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 }
    )
  }
}
