import { NextResponse } from 'next/server'
import { prisma } from '@/lib/db'

export const runtime = 'nodejs'

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const query = searchParams.get('q')
    const limit = parseInt(searchParams.get('limit') || '10')

    if (!query) {
      return NextResponse.json({ error: 'Termenul de căutare este obligatoriu' }, { status: 400 })
    }

    // Use full-text search function
    const results = await prisma.$queryRaw<Array<{
      verse_id: string
      book_name: string
      chapter_num: number
      verse_num: number
      verse_text: string
      rank: number
    }>>`
      SELECT * FROM search_verses(${query}, ${limit})
    `

    return NextResponse.json({ results })
  } catch (error) {
    console.error('Search error:', error)

    // Fallback to simple search if full-text search fails
    try {
      const fallbackResults = await prisma.bibleVerse.findMany({
        where: {
          text: {
            contains: query,
            mode: 'insensitive'
          }
        },
        include: {
          chapter: {
            include: {
              book: true
            }
          }
        },
        take: limit,
        orderBy: {
          id: 'asc'
        }
      })

      const formattedResults = fallbackResults.map(verse => ({
        verse_id: verse.id,
        book_name: verse.chapter.book.name,
        chapter_num: verse.chapter.chapterNum,
        verse_num: verse.verseNum,
        verse_text: verse.text,
        rank: 0.5
      }))

      return NextResponse.json({ results: formattedResults })
    } catch (fallbackError) {
      console.error('Fallback search error:', fallbackError)
      return NextResponse.json({ error: 'Eroare de server' }, { status: 500 })
    }
  }
}
