/**
 * Browser-Verhaltens-Matrix — On-demand LIVE-Lauf (Re-Crawl je Engine)
 * POST /api/sdk/v1/agent/snapshots/{snapshotId}/browser-behavior/run
 *   → backend /api/compliance/agent/snapshots/{snapshotId}/browser-behavior/run
 *
 * Teuer (mehrere Browser × 3 Phasen) → langer Timeout. Persistenz passiert
 * im Backend; die Antwort ist die frische Matrix.
 */

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

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

// Vercel-only Hinweis; self-hosted ignoriert es — schadet nicht.
export const maxDuration = 400

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ snapshotId: string }> },
) {
  const { snapshotId } = await params
  let body: unknown = {}
  try { body = await request.json() } catch { body = {} }
  try {
    const response = await fetch(
      `${BACKEND_URL}/api/compliance/agent/snapshots/${snapshotId}/browser-behavior/run`,
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body ?? {}),
        signal: AbortSignal.timeout(380_000),
      },
    )
    const data = await response.json()
    return NextResponse.json(data, { status: response.status })
  } catch (e) {
    return NextResponse.json(
      { error: `Browser-Test fehlgeschlagen: ${String(e)}` },
      { status: 504 },
    )
  }
}
