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 url = `${LS}/rag-agent/${tail}`
  const init: RequestInit = { method: req.method, cache: 'no-store' }

  if (req.method !== 'GET' && req.method !== 'HEAD') {
    const body = await req.text()
    if (body) {
      ;(init as any).body = body
      ;(init as any).headers = { 'Content-Type': req.headers.get('content-type') ?? 'application/json' }
    }
  }

  const res = await fetch(url, init)
  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)
}
