/**
 * API Route: Consent History
 *
 * GET /api/sdk/v1/einwilligungen/consent/{id}/history
 * Proxies to backend-compliance: GET /api/compliance/einwilligungen/consents/{id}/history
 */

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

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

function getTenantId(request: NextRequest): string {
  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')
  return (clientTenantId && uuidRegex.test(clientTenantId))
    ? clientTenantId
    : (process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e')
}

/**
 * GET /api/sdk/v1/einwilligungen/consent/{id}/history
 * Gibt die Änderungshistorie einer Einwilligung zurück.
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const tenantId = getTenantId(request)
    const response = await fetch(
      `${BACKEND_URL}/api/compliance/einwilligungen/consents/${id}/history`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'X-Tenant-ID': tenantId,
        },
        signal: AbortSignal.timeout(30000),
      }
    )

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

    const data = await response.json()
    return NextResponse.json(data)
  } catch (error) {
    console.error('Error fetching consent history:', error)
    return NextResponse.json({ error: 'Failed to fetch consent history' }, { status: 500 })
  }
}
