import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { verifyToken } from '@/lib/auth'

// POST /api/highlights/bulk?locale=en - Get highlights for multiple verses
export async function POST(req: NextRequest) {
  try {
    const authHeader = req.headers.get('authorization')
    if (!authHeader) {
      return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
    }

    const token = authHeader.replace('Bearer ', '')
    const decoded = await verifyToken(token)
    if (!decoded) {
      return NextResponse.json({ success: false, error: 'Invalid token' }, { status: 401 })
    }

    const body = await req.json()
    const { verseIds } = body

    if (!Array.isArray(verseIds)) {
      return NextResponse.json({ success: false, error: 'verseIds must be an array' }, { status: 400 })
    }

    const highlights = await prisma.highlight.findMany({
      where: {
        userId: decoded.userId,
        verseId: { in: verseIds }
      }
    })

    // Convert array to object keyed by verseId for easier lookup
    const highlightsMap: { [key: string]: any } = {}
    highlights.forEach(highlight => {
      highlightsMap[highlight.verseId] = highlight
    })

    return NextResponse.json({ success: true, highlights: highlightsMap })
  } catch (error) {
    console.error('Error fetching highlights:', error)
    return NextResponse.json({ success: false, error: 'Failed to fetch highlights' }, { status: 500 })
  }
}
