/**
 * API Route: Datenpunktkatalog
 *
 * GET  - Katalog abrufen (inkl. kundenspezifischer Datenpunkte)
 * POST - Katalog speichern/aktualisieren
 */

import { NextRequest, NextResponse } from 'next/server'
import {
  DataPointCatalog,
  CompanyInfo,
  CookieBannerConfig,
  DataPoint,
} from '@/lib/sdk/einwilligungen/types'
import { createDefaultCatalog, PREDEFINED_DATA_POINTS } from '@/lib/sdk/einwilligungen/catalog/loader'

// In-Memory Storage (in Produktion: Datenbank)
const catalogStorage = new Map<string, {
  catalog: DataPointCatalog
  companyInfo: CompanyInfo | null
  cookieBannerConfig: CookieBannerConfig | null
}>()

/**
 * GET /api/sdk/v1/einwilligungen/catalog
 *
 * Laedt den Datenpunktkatalog fuer einen Tenant
 */
export async function GET(request: NextRequest) {
  try {
    const tenantId = request.headers.get('X-Tenant-ID')

    if (!tenantId) {
      return NextResponse.json(
        { error: 'Tenant ID required' },
        { status: 400 }
      )
    }

    // Hole gespeicherte Daten oder erstelle Default
    let stored = catalogStorage.get(tenantId)

    if (!stored) {
      // Erstelle Default-Katalog
      const defaultCatalog = createDefaultCatalog(tenantId)
      stored = {
        catalog: defaultCatalog,
        companyInfo: null,
        cookieBannerConfig: null,
      }
      catalogStorage.set(tenantId, stored)
    }

    return NextResponse.json({
      catalog: stored.catalog,
      companyInfo: stored.companyInfo,
      cookieBannerConfig: stored.cookieBannerConfig,
    })
  } catch (error) {
    console.error('Error loading catalog:', error)
    return NextResponse.json(
      { error: 'Failed to load catalog' },
      { status: 500 }
    )
  }
}

/**
 * POST /api/sdk/v1/einwilligungen/catalog
 *
 * Speichert den Datenpunktkatalog fuer einen Tenant
 */
export async function POST(request: NextRequest) {
  try {
    const tenantId = request.headers.get('X-Tenant-ID')

    if (!tenantId) {
      return NextResponse.json(
        { error: 'Tenant ID required' },
        { status: 400 }
      )
    }

    const body = await request.json()
    const { catalog, companyInfo, cookieBannerConfig } = body

    if (!catalog) {
      return NextResponse.json(
        { error: 'Catalog data required' },
        { status: 400 }
      )
    }

    // Validiere den Katalog
    if (!catalog.tenantId || catalog.tenantId !== tenantId) {
      return NextResponse.json(
        { error: 'Tenant ID mismatch' },
        { status: 400 }
      )
    }

    // Aktualisiere den Katalog
    const updatedCatalog: DataPointCatalog = {
      ...catalog,
      updatedAt: new Date(),
    }

    // Speichere
    catalogStorage.set(tenantId, {
      catalog: updatedCatalog,
      companyInfo: companyInfo || null,
      cookieBannerConfig: cookieBannerConfig || null,
    })

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

/**
 * POST /api/sdk/v1/einwilligungen/catalog/customize
 *
 * Fuegt einen kundenspezifischen Datenpunkt hinzu
 */
export async function PUT(request: NextRequest) {
  try {
    const tenantId = request.headers.get('X-Tenant-ID')

    if (!tenantId) {
      return NextResponse.json(
        { error: 'Tenant ID required' },
        { status: 400 }
      )
    }

    const body = await request.json()
    const { action, dataPoint, dataPointId } = body

    let stored = catalogStorage.get(tenantId)

    if (!stored) {
      const defaultCatalog = createDefaultCatalog(tenantId)
      stored = {
        catalog: defaultCatalog,
        companyInfo: null,
        cookieBannerConfig: null,
      }
    }

    switch (action) {
      case 'add': {
        if (!dataPoint) {
          return NextResponse.json(
            { error: 'Data point required' },
            { status: 400 }
          )
        }

        // Generiere eindeutige ID
        const newDataPoint: DataPoint = {
          ...dataPoint,
          id: `custom-${tenantId}-${Date.now()}`,
          isCustom: true,
        }

        stored.catalog.customDataPoints.push(newDataPoint)
        stored.catalog.updatedAt = new Date()
        catalogStorage.set(tenantId, stored)

        return NextResponse.json({
          success: true,
          dataPoint: newDataPoint,
        })
      }

      case 'update': {
        if (!dataPointId || !dataPoint) {
          return NextResponse.json(
            { error: 'Data point ID and data required' },
            { status: 400 }
          )
        }

        // Pruefe ob es ein kundenspezifischer Datenpunkt ist
        const customIndex = stored.catalog.customDataPoints.findIndex(
          (dp) => dp.id === dataPointId
        )

        if (customIndex !== -1) {
          stored.catalog.customDataPoints[customIndex] = {
            ...stored.catalog.customDataPoints[customIndex],
            ...dataPoint,
          }
        } else {
          // Vordefinierter Datenpunkt - nur isActive aendern
          const predefinedIndex = stored.catalog.dataPoints.findIndex(
            (dp) => dp.id === dataPointId
          )
          if (predefinedIndex !== -1 && 'isActive' in dataPoint) {
            stored.catalog.dataPoints[predefinedIndex] = {
              ...stored.catalog.dataPoints[predefinedIndex],
              isActive: dataPoint.isActive,
            }
          }
        }

        stored.catalog.updatedAt = new Date()
        catalogStorage.set(tenantId, stored)

        return NextResponse.json({
          success: true,
        })
      }

      case 'delete': {
        if (!dataPointId) {
          return NextResponse.json(
            { error: 'Data point ID required' },
            { status: 400 }
          )
        }

        stored.catalog.customDataPoints = stored.catalog.customDataPoints.filter(
          (dp) => dp.id !== dataPointId
        )
        stored.catalog.updatedAt = new Date()
        catalogStorage.set(tenantId, stored)

        return NextResponse.json({
          success: true,
        })
      }

      default:
        return NextResponse.json(
          { error: 'Invalid action' },
          { status: 400 }
        )
    }
  } catch (error) {
    console.error('Error customizing catalog:', error)
    return NextResponse.json(
      { error: 'Failed to customize catalog' },
      { status: 500 }
    )
  }
}
