/**
 * Proxy: GET /api/sdk/v1/einwilligungen/export?format=csv|json&kind=consents|history
 *   -> backend /api/compliance/einwilligungen/export/<file>
 *
 * Streams the backend response straight through (CSV or JSON download).
 */
import { NextRequest, NextResponse } from 'next/server'

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

function getTenantHeader(request: NextRequest): HeadersInit {
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
  const clientTenantId = request.headers.get('x-tenant-id') || request.headers.get('X-Tenant-ID')
  const tenantId = (clientTenantId && uuidRegex.test(clientTenantId))
    ? clientTenantId
    : (process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e')
  return { 'X-Tenant-ID': tenantId }
}

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url)
  const fmt = (searchParams.get('format') || 'csv').toLowerCase()
  const kind = (searchParams.get('kind') || 'consents').toLowerCase()

  const filename = `${kind}.${fmt === 'json' ? 'json' : 'csv'}`
  const upstreamPath = `/api/compliance/einwilligungen/export/${filename}`

  const passthroughParams = new URLSearchParams()
  for (const k of ['user_id', 'granted', 'since', 'consent_id']) {
    const v = searchParams.get(k)
    if (v) passthroughParams.set(k, v)
  }
  const qs = passthroughParams.toString()
  const url = `${BACKEND_URL}${upstreamPath}${qs ? `?${qs}` : ''}`

  try {
    const r = await fetch(url, { headers: getTenantHeader(request) })
    if (!r.ok) {
      const text = await r.text()
      return NextResponse.json({ error: text || `HTTP ${r.status}` }, { status: r.status })
    }
    return new NextResponse(r.body, {
      status: 200,
      headers: {
        'Content-Type': r.headers.get('content-type') || 'application/octet-stream',
        'Content-Disposition': r.headers.get('content-disposition') || `attachment; filename=${filename}`,
      },
    })
  } catch (e) {
    return NextResponse.json(
      { error: 'Export-Proxy fehlgeschlagen', detail: String(e) },
      { status: 503 },
    )
  }
}
