/**
 * API Route: Datenpunktkatalog
 *
 * Proxies to backend-compliance for DB persistence.
 * GET  - Katalog abrufen
 * POST - Katalog speichern (forward as PUT to backend)
 * PUT  - Katalog-Einzeloperationen (add/update/delete)
 */

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/catalog
 */
export async function GET(request: NextRequest) {
  try {
    const headers = getHeaders(request)
    const response = await fetch(
      `${BACKEND_URL}/api/compliance/einwilligungen/catalog`,
      { 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 NextResponse.json(data)
  } catch (error) {
    console.error('Error loading catalog:', error)
    return NextResponse.json({ error: 'Failed to load catalog' }, { status: 500 })
  }
}

/**
 * POST /api/sdk/v1/einwilligungen/catalog
 * Saves catalog via PUT to backend
 */
export async function POST(request: NextRequest) {
  try {
    const headers = getHeaders(request)
    const body = await request.json()

    // Extract catalog data for backend format
    const { catalog, companyInfo } = body
    const backendPayload: Record<string, unknown> = {
      selected_data_point_ids: catalog?.dataPoints
        ?.filter((dp: { isActive?: boolean }) => dp.isActive)
        ?.map((dp: { id: string }) => dp.id) || [],
      custom_data_points: catalog?.customDataPoints || [],
    }

    const catalogResponse = await fetch(
      `${BACKEND_URL}/api/compliance/einwilligungen/catalog`,
      {
        method: 'PUT',
        headers,
        body: JSON.stringify(backendPayload),
        signal: AbortSignal.timeout(30000),
      }
    )

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

    // Save company info if provided
    if (companyInfo) {
      await fetch(`${BACKEND_URL}/api/compliance/einwilligungen/company`, {
        method: 'PUT',
        headers,
        body: JSON.stringify({ data: companyInfo }),
        signal: AbortSignal.timeout(30000),
      })
    }

    const result = await catalogResponse.json()
    return NextResponse.json({ success: true, catalog: result })
  } catch (error) {
    console.error('Error saving catalog:', error)
    return NextResponse.json({ error: 'Failed to save catalog' }, { status: 500 })
  }
}

/**
 * PUT /api/sdk/v1/einwilligungen/catalog
 * Katalog-Einzeloperationen (add/update/delete custom data points)
 */
export async function PUT(request: NextRequest) {
  try {
    const headers = getHeaders(request)
    const body = await request.json()
    const { action, dataPoint, dataPointId, selectedIds, customDataPoints } = body

    // For bulk updates (selectedIds + customDataPoints), use upsert
    if (selectedIds !== undefined || customDataPoints !== undefined) {
      const response = await fetch(
        `${BACKEND_URL}/api/compliance/einwilligungen/catalog`,
        {
          method: 'PUT',
          headers,
          body: JSON.stringify({
            selected_data_point_ids: selectedIds || [],
            custom_data_points: customDataPoints || [],
          }),
          signal: AbortSignal.timeout(30000),
        }
      )
      const data = await response.json()
      return NextResponse.json({ success: true, ...data })
    }

    // For individual add/update/delete, fetch current state and modify
    const currentResponse = await fetch(
      `${BACKEND_URL}/api/compliance/einwilligungen/catalog`,
      { method: 'GET', headers, signal: AbortSignal.timeout(30000) }
    )
    const current = await currentResponse.json()
    const currentCustom: unknown[] = current.custom_data_points || []
    const currentSelected: string[] = current.selected_data_point_ids || []

    let updatedCustom = [...currentCustom]
    let updatedSelected = [...currentSelected]

    switch (action) {
      case 'add':
        if (dataPoint) {
          updatedCustom.push({ ...dataPoint, id: `custom-${Date.now()}`, isCustom: true })
        }
        break
      case 'update':
        if (dataPointId && dataPoint) {
          updatedCustom = updatedCustom.map((dp: unknown) =>
            (dp as { id: string }).id === dataPointId ? { ...(dp as object), ...dataPoint } : dp
          )
        }
        break
      case 'delete':
        if (dataPointId) {
          updatedCustom = updatedCustom.filter((dp: unknown) => (dp as { id: string }).id !== dataPointId)
          updatedSelected = updatedSelected.filter((id) => id !== dataPointId)
        }
        break
    }

    const response = await fetch(
      `${BACKEND_URL}/api/compliance/einwilligungen/catalog`,
      {
        method: 'PUT',
        headers,
        body: JSON.stringify({
          selected_data_point_ids: updatedSelected,
          custom_data_points: updatedCustom,
        }),
        signal: AbortSignal.timeout(30000),
      }
    )
    const data = await response.json()
    return NextResponse.json({ success: true, ...data })
  } catch (error) {
    console.error('Error customizing catalog:', error)
    return NextResponse.json({ error: 'Failed to customize catalog' }, { status: 500 })
  }
}
