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 bookId = searchParams.get('bookId')
    const chapter = searchParams.get('chapter')

    if (!bookId || !chapter) {
      return NextResponse.json(
        {
          success: false,
          error: 'Missing bookId or chapter parameter',
          verses: []
        },
        { status: 400 }
      )
    }

    // Find the chapter (bookId is now a string UUID)
    const chapterRecord = await prisma.bibleChapter.findFirst({
      where: {
        bookId: bookId,
        chapterNum: parseInt(chapter)
      },
      include: {
        book: {
          include: {
            version: true
          }
        }
      }
    })

    if (!chapterRecord) {
      return NextResponse.json({
        success: true,
        verses: [],
        book: null,
        chapter: null
      })
    }

    // Get verses for this chapter
    const verses = await prisma.bibleVerse.findMany({
      where: {
        chapterId: chapterRecord.id
      },
      orderBy: {
        verseNum: 'asc'
      }
    })

    return NextResponse.json({
      success: true,
      book: {
        id: chapterRecord.book.id,
        name: chapterRecord.book.name,
        testament: chapterRecord.book.testament,
        orderNum: chapterRecord.book.orderNum
      },
      chapter: {
        id: chapterRecord.id,
        chapterNum: chapterRecord.chapterNum
      },
      version: {
        id: chapterRecord.book.version.id,
        name: chapterRecord.book.version.name,
        abbreviation: chapterRecord.book.version.abbreviation,
        language: chapterRecord.book.version.language
      },
      verses: verses.map(verse => ({
        id: verse.id,
        verseNum: verse.verseNum,
        text: verse.text
      }))
    })
  } catch (error) {
    console.error('Error fetching verses:', error)
    return NextResponse.json(
      {
        success: false,
        error: 'Failed to fetch verses',
        verses: []
      },
      { status: 500 }
    )
  }
}
