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

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

function buildUrl(request: NextRequest, params: { path?: string[] }) {
  const subPath = params.path?.join('/') || ''
  const { searchParams } = new URL(request.url)
  const qs = searchParams.toString()
  return `${SDK_URL}/sdk/v1/maximizer/${subPath}${qs ? `?${qs}` : ''}`
}

function forwardHeaders(request: NextRequest): Record<string, string> {
  const headers: Record<string, string> = { 'Content-Type': 'application/json' }
  headers['X-Tenant-ID'] = request.headers.get('X-Tenant-ID') || DEFAULT_TENANT_ID
  headers['X-User-ID'] = request.headers.get('X-User-ID') || DEFAULT_USER_ID
  return headers
}

async function proxy(request: NextRequest, params: { path?: string[] }, method: string) {
  try {
    const url = buildUrl(request, params)
    const init: RequestInit = { method, headers: forwardHeaders(request) }
    if (method !== 'GET' && method !== 'DELETE') {
      init.body = await request.text()
    }
    const response = await fetch(url, init)
    if (!response.ok) {
      const errorText = await response.text()
      return NextResponse.json({ error: 'Maximizer backend error', details: errorText }, { status: response.status })
    }
    if (response.status === 204) return new NextResponse(null, { status: 204 })
    const data = await response.json()
    return NextResponse.json(data)
  } catch (error) {
    console.error('Maximizer proxy error:', error)
    return NextResponse.json({ error: 'Failed to connect to Maximizer backend' }, { status: 503 })
  }
}

export async function GET(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  return proxy(request, await params, 'GET')
}

export async function POST(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  return proxy(request, await params, 'POST')
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  return proxy(request, await params, 'DELETE')
}
