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

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

// Catch-all proxy: /api/form-templates/xxx → :3200/form-templates/xxx
// Handles: /:id, /:id/generate, /calibrate/status, /calibrate/run,
//          /calibrate/:id, /logs/matter/:matterId, /library/reseed, /:id/cached-pdf

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}/form-templates/${tail}${search ? `?${search}` : ''}`

  const isBlob = tail.includes('/generate') || tail.endsWith('/pdf')
  const upstreamInit: RequestInit = { method: req.method, cache: 'no-store' }

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

  const res = await fetch(url, upstreamInit)

  if (isBlob && res.ok) {
    const buffer = await res.arrayBuffer()
    return new NextResponse(buffer, {
      status: res.status,
      headers: {
        'Content-Type': res.headers.get('Content-Type') ?? 'application/pdf',
        'Content-Disposition': res.headers.get('Content-Disposition') ?? 'attachment',
      },
    })
  }

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