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

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

/**
 * Proxy: GET /api/sdk/v1/wiki?endpoint=...
 *
 * Routes to backend wiki endpoints:
 *   endpoint=categories  → GET /api/compliance/v1/wiki/categories
 *   endpoint=articles    → GET /api/compliance/v1/wiki/articles(?category_id=...)
 *   endpoint=search      → GET /api/compliance/v1/wiki/search?q=...
 *   endpoint=article&id= → GET /api/compliance/v1/wiki/articles/{id}
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const endpoint = searchParams.get('endpoint') || 'categories'

    let backendPath: string

    switch (endpoint) {
      case 'categories':
        backendPath = '/api/compliance/v1/wiki/categories'
        break

      case 'articles': {
        const categoryId = searchParams.get('category_id')
        backendPath = '/api/compliance/v1/wiki/articles'
        if (categoryId) {
          backendPath += `?category_id=${encodeURIComponent(categoryId)}`
        }
        break
      }

      case 'article': {
        const articleId = searchParams.get('id')
        if (!articleId) {
          return NextResponse.json(
            { error: 'Missing article id' },
            { status: 400 }
          )
        }
        backendPath = `/api/compliance/v1/wiki/articles/${encodeURIComponent(articleId)}`
        break
      }

      case 'search': {
        const query = searchParams.get('q')
        if (!query) {
          return NextResponse.json(
            { error: 'Missing search query' },
            { status: 400 }
          )
        }
        backendPath = `/api/compliance/v1/wiki/search?q=${encodeURIComponent(query)}`
        break
      }

      default:
        return NextResponse.json(
          { error: `Unknown endpoint: ${endpoint}` },
          { status: 400 }
        )
    }

    const response = await fetch(`${BACKEND_URL}${backendPath}`)

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

    return NextResponse.json(await response.json())
  } catch (error) {
    console.error('Wiki proxy error:', error)
    return NextResponse.json(
      { error: 'Failed to connect to backend' },
      { status: 503 }
    )
  }
}
