/**
 * Banner API Proxy — catch-all route for cookie banner endpoints.
 *
 * Maps: /api/sdk/v1/banner/<path> → backend-compliance:8002/api/compliance/banner/<path>
 *
 * Solves: Browser cannot call backend-compliance:8093 directly due to
 * self-signed SSL certificates. This proxy runs server-side where
 * certificate validation is not an issue.
 */

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

const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
const DEFAULT_TENANT = process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'

async function proxyRequest(
  request: NextRequest,
  pathSegments: string[] | undefined,
  method: string,
) {
  const pathStr = pathSegments?.join('/') || ''
  const qs = request.nextUrl.searchParams.toString()
  const base = `${BACKEND_URL}/api/compliance/banner`
  const url = pathStr
    ? `${base}/${pathStr}${qs ? `?${qs}` : ''}`
    : `${base}${qs ? `?${qs}` : ''}`

  try {
    const headers: HeadersInit = {
      'X-Tenant-ID': request.headers.get('x-tenant-id') || DEFAULT_TENANT,
    }
    const ct = request.headers.get('Content-Type')
    if (ct) headers['Content-Type'] = ct

    const opts: RequestInit = { method, headers, signal: AbortSignal.timeout(30000) }

    if (method === 'POST' || method === 'PUT') {
      const body = await request.text()
      if (body) opts.body = body
    }

    const res = await fetch(url, opts)
    const text = await res.text()
    let data
    try { data = JSON.parse(text) } catch { data = { raw: text } }

    if (!res.ok) {
      return NextResponse.json(
        { error: `Backend ${res.status}`, ...data },
        { status: res.status },
      )
    }
    return NextResponse.json(data)
  } catch (err: any) {
    console.error('Banner proxy error:', err?.message)
    return NextResponse.json(
      { error: 'Backend nicht erreichbar' },
      { status: 503 },
    )
  }
}

export async function GET(req: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  return proxyRequest(req, (await params).path, 'GET')
}
export async function POST(req: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  return proxyRequest(req, (await params).path, 'POST')
}
export async function PUT(req: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  return proxyRequest(req, (await params).path, 'PUT')
}
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  return proxyRequest(req, (await params).path, 'DELETE')
}
