/**
 * API Route: Cookie Banner Configuration
 *
 * Proxies to backend-compliance for DB persistence.
 * GET  - Cookie Banner Konfiguration abrufen
 * POST - Cookie Banner Konfiguration speichern
 * PUT  - Einzelne Kategorie aktualisieren
 */

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

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

function getHeaders(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 {
    'Content-Type': 'application/json',
    'X-Tenant-ID': tenantId,
  }
}

/**
 * GET /api/sdk/v1/einwilligungen/cookie-banner/config
 */
export async function GET(request: NextRequest) {
  try {
    const headers = getHeaders(request)
    const response = await fetch(
      `${BACKEND_URL}/api/compliance/einwilligungen/cookies`,
      { method: 'GET', headers, 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 in the format the frontend expects (CookieBannerConfig-like)
    return NextResponse.json({
      categories: data.categories || [],
      config: data.config || {},
      updatedAt: data.updated_at,
    })
  } catch (error) {
    console.error('Error loading cookie banner config:', error)
    return NextResponse.json({ error: 'Failed to load cookie banner config' }, { status: 500 })
  }
}

/**
 * POST /api/sdk/v1/einwilligungen/cookie-banner/config
 */
export async function POST(request: NextRequest) {
  try {
    const headers = getHeaders(request)
    const body = await request.json()
    const { categories, config, styling, texts } = body

    const payload = {
      categories: categories || [],
      config: { ...(config || {}), styling: styling || {}, texts: texts || {} },
    }

    const response = await fetch(
      `${BACKEND_URL}/api/compliance/einwilligungen/cookies`,
      {
        method: 'PUT',
        headers,
        body: JSON.stringify(payload),
        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({
      success: true,
      categories: data.categories || [],
      config: data.config || {},
      updatedAt: data.updated_at,
    })
  } catch (error) {
    console.error('Error saving cookie banner config:', error)
    return NextResponse.json({ error: 'Failed to save cookie banner config' }, { status: 500 })
  }
}

/**
 * PUT /api/sdk/v1/einwilligungen/cookie-banner/config
 * Aktualisiert einzelne Kategorien
 */
export async function PUT(request: NextRequest) {
  try {
    const headers = getHeaders(request)
    const body = await request.json()
    const { categoryId, enabled, categories, config } = body

    // If full categories array is provided, save it directly
    if (categories !== undefined) {
      const response = await fetch(
        `${BACKEND_URL}/api/compliance/einwilligungen/cookies`,
        {
          method: 'PUT',
          headers,
          body: JSON.stringify({ categories, config: config || {} }),
          signal: AbortSignal.timeout(30000),
        }
      )
      const data = await response.json()
      return NextResponse.json({ success: true, ...data })
    }

    // Single category toggle: fetch current, update, save back
    if (!categoryId || typeof enabled !== 'boolean') {
      return NextResponse.json({ error: 'categoryId and enabled required' }, { status: 400 })
    }

    const currentResponse = await fetch(
      `${BACKEND_URL}/api/compliance/einwilligungen/cookies`,
      { method: 'GET', headers, signal: AbortSignal.timeout(30000) }
    )
    const current = await currentResponse.json()

    const updatedCategories = (current.categories || []).map((cat: { id: string; isRequired?: boolean; defaultEnabled?: boolean }) => {
      if (cat.id !== categoryId) return cat
      if (cat.isRequired && !enabled) return cat  // Essential cookies cannot be disabled
      return { ...cat, defaultEnabled: enabled }
    })

    const saveResponse = await fetch(
      `${BACKEND_URL}/api/compliance/einwilligungen/cookies`,
      {
        method: 'PUT',
        headers,
        body: JSON.stringify({ categories: updatedCategories, config: current.config || {} }),
        signal: AbortSignal.timeout(30000),
      }
    )

    const data = await saveResponse.json()
    return NextResponse.json({
      success: true,
      category: updatedCategories.find((c: { id: string }) => c.id === categoryId),
      ...data,
    })
  } catch (error) {
    console.error('Error updating cookie category:', error)
    return NextResponse.json({ error: 'Failed to update cookie category' }, { status: 500 })
  }
}
