/**
 * Agent Scan API Proxy — async scan with polling
 *
 * POST /api/sdk/v1/agent/scan → starts scan, returns scan_id
 * GET  /api/sdk/v1/agent/scan?scan_id=xxx → poll status/results
 */

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

    // Start async scan — returns immediately with scan_id
    const response = await fetch(`${BACKEND_URL}/api/compliance/agent/scan`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body,
      signal: AbortSignal.timeout(300000), // 5 min — multi-page scan + LLM calls
    })

    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 scan proxy error:', error)
    return NextResponse.json(
      { error: 'Scan konnte nicht gestartet werden' },
      { status: 503 }
    )
  }
}

export async function GET(request: NextRequest) {
  const scanId = request.nextUrl.searchParams.get('scan_id')
  if (!scanId) {
    return NextResponse.json({ error: 'scan_id parameter required' }, { status: 400 })
  }

  try {
    const response = await fetch(
      `${BACKEND_URL}/api/compliance/agent/scan/${scanId}`,
      { signal: AbortSignal.timeout(10000) }
    )

    if (!response.ok) {
      return NextResponse.json(
        { error: `Backend: ${response.status}` },
        { status: response.status }
      )
    }

    const data = await response.json()
    return NextResponse.json(data)
  } catch (error) {
    return NextResponse.json(
      { error: 'Status-Abfrage fehlgeschlagen' },
      { status: 503 }
    )
  }
}
