/**
 * DSFA Corpus API Proxy
 *
 * Proxies requests to klausur-service for DSFA RAG operations.
 * Endpoints: /api/v1/dsfa-rag/stats, /api/v1/dsfa-rag/sources
 */

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

const KLAUSUR_SERVICE_URL = process.env.KLAUSUR_SERVICE_URL || 'http://klausur-service:8086'

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url)
  const action = searchParams.get('action')

  try {
    let url = `${KLAUSUR_SERVICE_URL}/api/v1/dsfa-rag`

    switch (action) {
      case 'status':
        url += '/stats'
        break
      case 'sources':
        url += '/sources'
        break
      case 'source-detail': {
        const code = searchParams.get('code')
        if (!code) {
          return NextResponse.json({ error: 'Missing code parameter' }, { status: 400 })
        }
        url += `/sources/${encodeURIComponent(code)}`
        break
      }
      default:
        return NextResponse.json({ error: 'Unknown action' }, { status: 400 })
    }

    const res = await fetch(url, {
      headers: {
        'Content-Type': 'application/json',
      },
      cache: 'no-store',
    })

    const data = await res.json()
    return NextResponse.json(data, { status: res.status })
  } catch (error) {
    console.error('DSFA corpus proxy error:', error)
    return NextResponse.json(
      { error: 'Failed to connect to klausur-service' },
      { status: 503 }
    )
  }
}

export async function POST(request: NextRequest) {
  const { searchParams } = new URL(request.url)
  const action = searchParams.get('action')

  try {
    let url = `${KLAUSUR_SERVICE_URL}/api/v1/dsfa-rag`

    switch (action) {
      case 'init': {
        url += '/init'
        const res = await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
        })
        const data = await res.json()
        return NextResponse.json(data, { status: res.status })
      }

      case 'ingest': {
        const body = await request.json()
        const sourceCode = body.source_code
        if (!sourceCode) {
          return NextResponse.json({ error: 'Missing source_code' }, { status: 400 })
        }
        url += `/sources/${encodeURIComponent(sourceCode)}/ingest`
        const res = await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body),
        })
        const data = await res.json()
        return NextResponse.json(data, { status: res.status })
      }

      default:
        return NextResponse.json({ error: 'Unknown action' }, { status: 400 })
    }
  } catch (error) {
    console.error('DSFA corpus proxy error:', error)
    return NextResponse.json(
      { error: 'Failed to connect to klausur-service' },
      { status: 503 }
    )
  }
}
