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

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

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

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams
    const search = searchParams.get('search')
    const province = searchParams.get('province')
    const type = searchParams.get('type')

    // Build cache key from params
    const cacheKey = `${search || ''}-${province || ''}-${type || ''}`

    // Check cache
    if (
      uniCache &&
      Date.now() - uniCache.timestamp < CACHE_TTL &&
      !search // Don't cache specific searches
    ) {
      return NextResponse.json({
        universities: uniCache.data,
        cached: true,
        fetchedAt: new Date(uniCache.timestamp).toISOString(),
      })
    }

    // Fetch from web
    const webResults = await fetchUniversityInfo(search || undefined)

    // Build DB query
    const dbWhere: Record<string, unknown> = {}
    if (province) dbWhere.province = province
    if (type) dbWhere.type = type
    if (search) dbWhere.name = { contains: search }

    const dbListings = await db.universityListing.findMany({
      where: dbWhere,
      orderBy: { name: 'asc' },
      take: 30,
    })

    // Merge results
    const mergedResults = [
      ...webResults.map((u) => ({
        name: u.name,
        description: u.description || u.snippet,
        sourceUrl: u.sourceUrl,
        sourceName: u.sourceName,
        type: 'web' as const,
        fetchedAt: u.fetchedAt,
      })),
      ...dbListings.map((u) => ({
        name: u.name,
        description: u.courses ? `Courses available: ${u.courses}` : undefined,
        province: u.province,
        type: u.type,
        courses: u.courses,
        requirements: u.requirements,
        applicationFee: u.applicationFee,
        tuitionRange: u.tuitionRange,
        website: u.website,
        sourceUrl: u.sourceUrl,
        lastVerified: u.lastVerified?.toISOString(),
        aiGenerated: u.aiGenerated,
        type2: 'database' as const,
        fetchedAt: u.createdAt.toISOString(),
      })),
    ]

    // Update cache (only for general queries)
    if (!search) {
      uniCache = {
        data: mergedResults as Array<Record<string, unknown>>,
        timestamp: Date.now(),
      }
    }

    return NextResponse.json({
      universities: mergedResults,
      cached: !!(!search && uniCache && Date.now() - uniCache.timestamp < CACHE_TTL),
      count: mergedResults.length,
      fetchedAt: new Date().toISOString(),
    })
  } catch (error) {
    console.error('Browse universities error:', error instanceof Error ? error.message : error)
    return NextResponse.json(
      { error: 'Failed to fetch university information.' },
      { status: 500 }
    )
  }
}
