/**
 * Agent Analyze API Proxy
 * POST /api/sdk/v1/agent/analyze → backend-compliance /api/compliance/agent/analyze
 */

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

const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'

export async function POST(request: NextRequest) {
  try {
    const body = await request.text()

    const response = await fetch(`${BACKEND_URL}/api/compliance/agent/analyze`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Tenant-Id': '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e',
        'X-User-Id': '00000000-0000-0000-0000-000000000001',
      },
      body,
      signal: AbortSignal.timeout(120000), // 2 min — LLM can be slow
    })

    if (!response.ok) {
      const errorText = await response.text()
      return NextResponse.json(
        { error: `Backend: ${response.status}`, detail: errorText },
        { status: response.status }
      )
    }

    const data = await response.json()
    return NextResponse.json(data)
  } catch (error) {
    console.error('Agent analyze proxy error:', error)
    return NextResponse.json(
      { error: 'Verbindung zum Backend fehlgeschlagen' },
      { status: 503 }
    )
  }
}
