/**
 * Whistleblower API Proxy - Catch-all route
 * Proxies all /api/sdk/v1/whistleblower/* requests to ai-compliance-sdk backend
 * Supports multipart/form-data for file uploads
 */

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

const SDK_BACKEND_URL = process.env.SDK_API_URL || 'http://ai-compliance-sdk:8090'

async function proxyRequest(
  request: NextRequest,
  pathSegments: string[] | undefined,
  method: string
) {
  const pathStr = pathSegments?.join('/') || ''
  const searchParams = request.nextUrl.searchParams.toString()
  const basePath = `${SDK_BACKEND_URL}/sdk/v1/whistleblower`
  const url = pathStr
    ? `${basePath}/${pathStr}${searchParams ? `?${searchParams}` : ''}`
    : `${basePath}${searchParams ? `?${searchParams}` : ''}`

  try {
    const headers: HeadersInit = {}
    const contentType = request.headers.get('content-type')

    // Forward auth headers
    const authHeader = request.headers.get('authorization')
    if (authHeader) {
      headers['Authorization'] = authHeader
    }

    const tenantHeader = request.headers.get('x-tenant-id')
    if (tenantHeader) {
      headers['X-Tenant-Id'] = tenantHeader
    }

    const fetchOptions: RequestInit = {
      method,
      headers,
      signal: AbortSignal.timeout(60000), // 60s for file uploads
    }

    if (['POST', 'PUT', 'PATCH'].includes(method)) {
      if (contentType?.includes('multipart/form-data')) {
        // Forward multipart form data (file uploads)
        const formData = await request.formData()
        fetchOptions.body = formData
        // Don't set Content-Type - let fetch set it with boundary
      } else if (contentType?.includes('application/json')) {
        headers['Content-Type'] = 'application/json'
        try {
          const text = await request.text()
          if (text && text.trim()) {
            fetchOptions.body = text
          }
        } catch {
          // Empty or invalid body
        }
      } else {
        headers['Content-Type'] = 'application/json'
      }
    } else {
      headers['Content-Type'] = 'application/json'
    }

    const response = await fetch(url, fetchOptions)

    // Handle non-JSON responses (e.g., PDF exports, file downloads)
    const responseContentType = response.headers.get('content-type')
    if (responseContentType?.includes('application/pdf') ||
        responseContentType?.includes('application/octet-stream') ||
        responseContentType?.includes('image/')) {
      const blob = await response.blob()
      return new NextResponse(blob, {
        status: response.status,
        headers: {
          'Content-Type': responseContentType,
          'Content-Disposition': response.headers.get('content-disposition') || '',
        },
      })
    }

    if (!response.ok) {
      const errorText = await response.text()
      let errorJson
      try {
        errorJson = JSON.parse(errorText)
      } catch {
        errorJson = { error: errorText }
      }
      return NextResponse.json(
        { error: `Backend Error: ${response.status}`, ...errorJson },
        { status: response.status }
      )
    }

    const data = await response.json()
    return NextResponse.json(data)
  } catch (error) {
    console.error('Whistleblower API proxy error:', error)
    return NextResponse.json(
      { error: 'Verbindung zum SDK Backend fehlgeschlagen' },
      { status: 503 }
    )
  }
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ path?: string[] }> }
) {
  const { path } = await params
  return proxyRequest(request, path, 'GET')
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ path?: string[] }> }
) {
  const { path } = await params
  return proxyRequest(request, path, 'POST')
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ path?: string[] }> }
) {
  const { path } = await params
  return proxyRequest(request, path, 'PUT')
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ path?: string[] }> }
) {
  const { path } = await params
  return proxyRequest(request, path, 'PATCH')
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ path?: string[] }> }
) {
  const { path } = await params
  return proxyRequest(request, path, 'DELETE')
}
