import { NextRequest, NextResponse } from 'next/server'
import { fetchBursaries } from '@/lib/ai/browse'
import { db } from '@/lib/db'

// In-memory cache
let bursaryCache: {
  data: Array<Record<string, unknown>>
  timestamp: number
} | null = null

const CACHE_TTL = 60 * 60 * 1000 // 1 hour

export async function GET(request: NextRequest) {
  try {
    // Check cache first
    if (bursaryCache && Date.now() - bursaryCache.timestamp < CACHE_TTL) {
      return NextResponse.json({
        bursaries: bursaryCache.data,
        cached: true,
        fetchedAt: new Date(bursaryCache.timestamp).toISOString(),
      })
    }

    // Fetch from web
    const searchParams = request.nextUrl.searchParams
    const province = searchParams.get('province')
    const field = searchParams.get('field')

    let webResults = await fetchBursaries()

    // Filter by province if provided
    if (province) {
      webResults = webResults.filter((b) =>
        b.description?.toLowerCase().includes(province.toLowerCase()) ||
        b.snippet?.toLowerCase().includes(province.toLowerCase()) ||
        b.title?.toLowerCase().includes(province.toLowerCase())
      )
    }

    // Filter by field of study if provided
    if (field) {
      webResults = webResults.filter((b) =>
        b.description?.toLowerCase().includes(field.toLowerCase()) ||
        b.snippet?.toLowerCase().includes(field.toLowerCase()) ||
        b.title?.toLowerCase().includes(field.toLowerCase())
      )
    }

    // Also fetch from database
    const dbListings = await db.bursaryListing.findMany({
      where: {
        ...(province ? { province } : {}),
        ...(field ? { fieldOfStudy: field } : {}),
      },
      orderBy: { createdAt: 'desc' },
      take: 20,
    })

    // Merge results
    const mergedResults = [
      ...webResults.map((b) => ({
        title: b.title,
        description: b.description || b.snippet,
        sourceUrl: b.sourceUrl,
        sourceName: b.sourceName,
        type: 'web' as const,
        fetchedAt: b.fetchedAt,
      })),
      ...dbListings.map((b) => ({
        title: b.title,
        description: b.description,
        sourceUrl: b.sourceUrl,
        provider: b.provider,
        closingDate: b.closingDate?.toISOString(),
        value: b.value,
        province: b.province,
        fieldOfStudy: b.fieldOfStudy,
        level: b.level,
        isVerified: b.isVerified,
        type: 'database' as const,
        fetchedAt: b.createdAt.toISOString(),
      })),
    ]

    // Update cache
    bursaryCache = {
      data: mergedResults as Array<Record<string, unknown>>,
      timestamp: Date.now(),
    }

    return NextResponse.json({
      bursaries: mergedResults,
      cached: false,
      count: mergedResults.length,
      fetchedAt: new Date().toISOString(),
    })
  } catch (error) {
    console.error('Browse bursaries error:', error instanceof Error ? error.message : error)
    return NextResponse.json(
      { error: 'Failed to fetch bursary information.' },
      { status: 500 }
    )
  }
}
