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

const LS = process.env.LEGAL_SERVICE_URL ?? 'http://localhost:3200'

type RouteCtx = { params: Promise<{ path: string[] }> }

async function proxy(req: NextRequest, segments: string[]) {
  const tail   = segments.join('/')
  const search = req.nextUrl.searchParams.toString()
  const url    = `${LS}/annual-compliance/${tail}${search ? `?${search}` : ''}`

  const init: RequestInit = { method: req.method, cache: 'no-store' }
  if (req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'DELETE') {
    try {
      const body = await req.json()
      init.body    = JSON.stringify(body)
      init.headers = { 'Content-Type': 'application/json' }
    } catch { /* no body */ }
  }

  const res = await fetch(url, init)
  if (res.status === 204) return new NextResponse(null, { status: 204 })
  const data = await res.json().catch(() => ({}))
  return NextResponse.json(data, { status: res.status })
}

export async function GET(req: NextRequest, ctx: RouteCtx) {
  const { path } = await ctx.params
  return proxy(req, path)
}
export async function POST(req: NextRequest, ctx: RouteCtx) {
  const { path } = await ctx.params
  return proxy(req, path)
}
export async function PATCH(req: NextRequest, ctx: RouteCtx) {
  const { path } = await ctx.params
  return proxy(req, path)
}
export async function DELETE(req: NextRequest, ctx: RouteCtx) {
  const { path } = await ctx.params
  return proxy(req, path)
}
