/** * RAG API Proxy - Catch-all route * Proxies all /api/sdk/v1/rag/* requests to ai-compliance-sdk backend (Port 8090) */ 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/rag` const url = pathStr ? `${basePath}/${pathStr}${searchParams ? `?${searchParams}` : ''}` : `${basePath}${searchParams ? `?${searchParams}` : ''}` try { const headers: HeadersInit = { 'Content-Type': 'application/json', } const authHeader = request.headers.get('authorization') if (authHeader) { headers['Authorization'] = authHeader } const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i const userHeader = request.headers.get('x-user-id') headers['X-User-ID'] = (userHeader && uuidRegex.test(userHeader)) ? userHeader : '00000000-0000-0000-0000-000000000001' const tenantHeader = request.headers.get('x-tenant-id') headers['X-Tenant-ID'] = (tenantHeader && uuidRegex.test(tenantHeader)) ? tenantHeader : (process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e') const fetchOptions: RequestInit = { method, headers, signal: AbortSignal.timeout(30000), } if (['POST', 'PUT', 'PATCH'].includes(method)) { const contentType = request.headers.get('content-type') if (contentType?.includes('application/json')) { try { const text = await request.text() if (text && text.trim()) { fetchOptions.body = text } } catch { // Empty or invalid body - continue without } } } const response = await fetch(url, fetchOptions) 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('RAG API proxy error:', error) return NextResponse.json( { error: 'Verbindung zum RAG 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') }