/**
 * Audit Session PDF Report API Route - Proxy to Backend
 */

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

const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:8000'

// Generate PDF report for audit session
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ sessionId: string }> }
) {
  try {
    const { sessionId } = await params
    const authHeader = request.headers.get('Authorization')
    const { searchParams } = new URL(request.url)

    const language = searchParams.get('language') || 'de'
    const includeSignatures = searchParams.get('include_signatures') !== 'false'

    const queryParams = new URLSearchParams({
      language,
      include_signatures: String(includeSignatures)
    })

    const response = await fetch(
      `${BACKEND_URL}/api/v1/compliance/audit/sessions/${sessionId}/report/pdf?${queryParams}`,
      {
        method: 'GET',
        headers: {
          ...(authHeader ? { 'Authorization': authHeader } : {})
        },
        signal: AbortSignal.timeout(60000) // 60s timeout for PDF generation
      }
    )

    if (!response.ok) {
      const errorText = await response.text()
      return NextResponse.json(
        { error: `Backend Error: ${response.status}`, details: errorText },
        { status: response.status }
      )
    }

    // Stream the PDF response
    const pdfBuffer = await response.arrayBuffer()
    const contentDisposition = response.headers.get('Content-Disposition') ||
      `attachment; filename=audit-report-${sessionId}.pdf`

    return new NextResponse(pdfBuffer, {
      status: 200,
      headers: {
        'Content-Type': 'application/pdf',
        'Content-Disposition': contentDisposition,
        'Content-Length': String(pdfBuffer.byteLength)
      }
    })
  } catch (error) {
    console.error('Audit PDF proxy error:', error)
    return NextResponse.json(
      { error: 'PDF-Generierung fehlgeschlagen' },
      { status: 503 }
    )
  }
}
