import { NextRequest, NextResponse } from 'next/server'
import {
  getAllControls,
  getControlById,
  getControlsByCategory,
  searchControls,
  getCategories,
} from '@/lib/sdk/tom-generator/controls/loader'
import { ControlCategory } from '@/lib/sdk/tom-generator/types'

/**
 * TOM Generator Controls API
 *
 * GET /api/sdk/v1/tom-generator/controls - List all controls
 * GET /api/sdk/v1/tom-generator/controls?id=xxx - Get single control
 * GET /api/sdk/v1/tom-generator/controls?category=xxx - Filter by category
 * GET /api/sdk/v1/tom-generator/controls?search=xxx - Search controls
 * GET /api/sdk/v1/tom-generator/controls?categories=true - Get categories list
 */

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const id = searchParams.get('id')
    const category = searchParams.get('category')
    const search = searchParams.get('search')
    const categoriesOnly = searchParams.get('categories')
    const language = (searchParams.get('language') || 'de') as 'de' | 'en'

    // Get categories list
    if (categoriesOnly === 'true') {
      const categories = getCategories()
      return NextResponse.json({
        success: true,
        data: categories,
      })
    }

    // Get single control by ID
    if (id) {
      const control = getControlById(id)
      if (!control) {
        return NextResponse.json(
          { success: false, error: `Control not found: ${id}` },
          { status: 404 }
        )
      }
      return NextResponse.json({
        success: true,
        data: {
          ...control,
          // Return localized name and description
          localizedName: control.name[language],
          localizedDescription: control.description[language],
        },
      })
    }

    // Filter by category
    if (category) {
      const controls = getControlsByCategory(category as ControlCategory)
      return NextResponse.json({
        success: true,
        data: controls.map((c) => ({
          ...c,
          localizedName: c.name[language],
          localizedDescription: c.description[language],
        })),
        meta: {
          category,
          count: controls.length,
        },
      })
    }

    // Search controls
    if (search) {
      const controls = searchControls(search, language)
      return NextResponse.json({
        success: true,
        data: controls.map((c) => ({
          ...c,
          localizedName: c.name[language],
          localizedDescription: c.description[language],
        })),
        meta: {
          query: search,
          count: controls.length,
        },
      })
    }

    // Return all controls
    const controls = getAllControls()
    const categories = getCategories()

    return NextResponse.json({
      success: true,
      data: controls.map((c) => ({
        ...c,
        localizedName: c.name[language],
        localizedDescription: c.description[language],
      })),
      meta: {
        totalControls: controls.length,
        categories: categories.length,
        language,
      },
    })
  } catch (error) {
    console.error('Failed to fetch controls:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to fetch controls' },
      { status: 500 }
    )
  }
}

export async function OPTIONS() {
  return NextResponse.json(
    { status: 'ok' },
    {
      headers: {
        Allow: 'GET, OPTIONS',
      },
    }
  )
}
