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

/**
 * Proxy to backend /api/abitur-docs
 * Lists and manages Abitur documents (NiBiS, etc.)
 */

const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:8000'

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

    // Forward all query params to backend
    const queryString = searchParams.toString()
    const url = `${BACKEND_URL}/api/abitur-docs/${queryString ? `?${queryString}` : ''}`

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    })

    if (!response.ok) {
      // Return mock data for development if backend is not available
      if (response.status === 404 || response.status === 502) {
        return NextResponse.json(getMockDocuments(searchParams))
      }
      throw new Error(`Backend responded with ${response.status}`)
    }

    const data = await response.json()

    // If backend returns empty array, use mock data for demo purposes
    // (Backend uses in-memory storage which is lost on restart)
    if (Array.isArray(data) && data.length === 0) {
      console.log('Backend returned empty array, using mock data')
      return NextResponse.json(getMockDocuments(searchParams))
    }

    // Handle paginated response with empty documents
    if (data.documents && Array.isArray(data.documents) && data.documents.length === 0 && data.total === 0) {
      console.log('Backend returned empty documents, using mock data')
      return NextResponse.json(getMockDocuments(searchParams))
    }

    return NextResponse.json(data)
  } catch (error) {
    console.error('Abitur docs list error:', error)
    // Return mock data for development
    return NextResponse.json(getMockDocuments(new URL(request.url).searchParams))
  }
}

function getMockDocuments(searchParams: URLSearchParams) {
  const page = parseInt(searchParams.get('page') || '1')
  const limit = parseInt(searchParams.get('limit') || '20')
  const fach = searchParams.get('fach')
  const jahr = searchParams.get('jahr')
  const bundesland = searchParams.get('bundesland')

  // Generate mock documents
  const allDocs = generateMockDocs()

  // Apply filters
  let filtered = allDocs
  if (fach) {
    filtered = filtered.filter(d => d.fach === fach)
  }
  if (jahr) {
    filtered = filtered.filter(d => d.jahr === parseInt(jahr))
  }
  if (bundesland) {
    filtered = filtered.filter(d => d.bundesland === bundesland)
  }

  // Paginate
  const start = (page - 1) * limit
  const docs = filtered.slice(start, start + limit)

  return {
    documents: docs,
    total: filtered.length,
    page,
    limit,
    total_pages: Math.ceil(filtered.length / limit),
  }
}

function generateMockDocs() {
  const faecher = ['deutsch', 'mathematik', 'englisch', 'biologie', 'physik', 'chemie', 'geschichte']
  const jahre = [2024, 2025]
  const niveaus = ['eA', 'gA']
  const typen = ['aufgabe', 'erwartungshorizont']
  const nummern = ['I', 'II', 'III']

  const docs = []
  let id = 1

  for (const jahr of jahre) {
    for (const fach of faecher) {
      for (const niveau of niveaus) {
        for (const nummer of nummern) {
          for (const typ of typen) {
            const suffix = typ === 'erwartungshorizont' ? '_EWH' : ''
            const dateiname = `${jahr}_${capitalize(fach)}_${niveau}_${nummer}${suffix}.pdf`

            docs.push({
              id: `doc-${id++}`,
              dateiname,
              original_dateiname: dateiname,
              bundesland: 'niedersachsen',
              fach,
              jahr,
              niveau,
              typ,
              aufgaben_nummer: nummer,
              status: 'indexed',
              confidence: 0.95,
              file_path: `/tmp/abitur-docs/${dateiname}`,
              file_size: Math.floor(Math.random() * 500000) + 100000,
              indexed: true,
              vector_ids: [`vec-${id}-1`, `vec-${id}-2`],
              created_at: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
              updated_at: new Date().toISOString(),
            })
          }
        }
      }
    }
  }

  return docs
}

function capitalize(str: string): string {
  return str.charAt(0).toUpperCase() + str.slice(1)
}
