/**
 * POST /api/scan/start
 *   Proxy to compliance backend /api/compliance/agent/saving-scan/start.
 *
 * Body: { url: string; email: string; consent?: boolean }
 *
 * Server-side proxy avoids cross-origin POST from breakpilot.ai to
 * api-dev.breakpilot.ai — same-origin from the browser, secure egress
 * from the Next.js server. Backend handles rate-limit + TDM + lead-DB.
 */
import { NextRequest, NextResponse } from 'next/server'

const BACKEND_URL =
  process.env.COMPLIANCE_BACKEND_URL || 'https://api-dev.breakpilot.ai'

export async function POST(request: NextRequest) {
  let body: unknown
  try {
    body = await request.json()
  } catch {
    return NextResponse.json(
      { error: 'Body muss JSON sein' }, { status: 400 },
    )
  }

  try {
    const res = await fetch(
      `${BACKEND_URL}/api/compliance/agent/saving-scan/start`,
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
        signal: AbortSignal.timeout(20000),
      },
    )
    const data = await res.json().catch(() => ({}))
    return NextResponse.json(data, { status: res.status })
  } catch {
    return NextResponse.json(
      { error: 'Backend nicht erreichbar' }, { status: 503 },
    )
  }
}
