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

async function proxy(request: NextRequest, method: string, id: string, body?: string) {
  const tenantId = tenantHeader(request)
  const init: RequestInit = {
    method,
    headers: { 'X-Tenant-ID': tenantId, 'Content-Type': 'application/json' },
  }
  if (body !== undefined) init.body = body
  try {
    const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}`, init)
    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 }
    )
  }
}

export async function GET(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  const { id } = await ctx.params
  return proxy(request, 'GET', id)
}

export async function PATCH(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  const { id } = await ctx.params
  const body = await request.text()
  return proxy(request, 'PATCH', id, body)
}

export async function DELETE(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  const { id } = await ctx.params
  return proxy(request, 'DELETE', id)
}
