/**
 * Banner Check API Proxy — calls consent-tester /scan endpoint
 *
 * POST /api/sdk/v1/agent/banner-check → runs 3-phase cookie banner test
 */

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.json()
    const { url, categories = [] } = body

    if (!url) {
      return NextResponse.json({ error: 'URL erforderlich' }, { status: 400 })
    }

    // Call backend which proxies to consent-tester
    const response = await fetch(`${BACKEND_URL}/api/compliance/agent/banner-check`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ url, categories }),
      signal: AbortSignal.timeout(120000), // 2 min for Playwright
    })

    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) {
    const msg = error instanceof Error ? error.message : 'Unknown error'
    return NextResponse.json({ error: msg }, { status: 500 })
  }
}
