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

const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'
const DEFAULT_TENANT = process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'

/**
 * Proxy: /api/sdk/v1/ucca/decision-tree/... → Go Backend /sdk/v1/ucca/decision-tree/...
 */
async function proxyRequest(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  const { path } = await params
  const subPath = path ? path.join('/') : ''
  const search = request.nextUrl.search || ''
  const targetUrl = `${SDK_URL}/sdk/v1/ucca/decision-tree/${subPath}${search}`

  const tenantID = request.headers.get('X-Tenant-ID') || DEFAULT_TENANT

  try {
    const headers: Record<string, string> = {
      'X-Tenant-ID': tenantID,
    }

    const fetchOptions: RequestInit = {
      method: request.method,
      headers,
    }

    if (request.method === 'POST' || request.method === 'PUT' || request.method === 'PATCH') {
      const body = await request.json()
      headers['Content-Type'] = 'application/json'
      fetchOptions.body = JSON.stringify(body)
    }

    const response = await fetch(targetUrl, fetchOptions)

    if (!response.ok) {
      const errorText = await response.text()
      console.error(`Decision tree proxy error [${request.method} ${subPath}]:`, errorText)
      return NextResponse.json(
        { error: 'Backend error', details: errorText },
        { status: response.status }
      )
    }

    const data = await response.json()
    return NextResponse.json(data, { status: response.status })
  } catch (error) {
    console.error('Decision tree proxy connection error:', error)
    return NextResponse.json(
      { error: 'Failed to connect to AI compliance backend' },
      { status: 503 }
    )
  }
}

export const GET = proxyRequest
export const POST = proxyRequest
export const DELETE = proxyRequest
