/**
 * Next.js Proxy: leitet POST /api/v1/founding-wizard/generate an Backend.
 *
 * Konvertiert das Backend-Response (base64 DOCX) in data: URLs,
 * die das Frontend direkt als Download anbieten kann.
 */

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

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

export async function POST(req: NextRequest) {
  try {
    const body = await req.json()

    const backendRes = await fetch(`${BACKEND_URL}/v1/founding-wizard/generate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    })

    if (!backendRes.ok) {
      const errorText = await backendRes.text()
      return NextResponse.json(
        { error: 'Backend-Generierung fehlgeschlagen', detail: errorText },
        { status: backendRes.status }
      )
    }

    const data = await backendRes.json()
    const documents = (data.documents || []).map((doc: {
      document_type: string
      title: string
      filename: string
      content_base64: string
      size_bytes: number
      generated_at: string
    }) => ({
      document_type: doc.document_type,
      title: doc.title,
      filename: doc.filename,
      download_url: `data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,${doc.content_base64}`,
      size_bytes: doc.size_bytes,
      generated_at: doc.generated_at,
    }))

    return NextResponse.json({
      documents,
      warnings: data.warnings || [],
    })
  } catch (e: unknown) {
    const message = e instanceof Error ? e.message : 'Unbekannter Fehler'
    return NextResponse.json(
      { error: 'Proxy-Fehler', detail: message },
      { status: 500 }
    )
  }
}
