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

export const runtime = 'nodejs'

function getErrorMessages(locale: string = 'ro') {
  const messages = {
    ro: {
      unauthorized: 'Nu ești autentificat',
      bookmarkRequired: 'Lista de versete este obligatorie',
      bookmarkError: 'Eroare la verificarea bookmark-urilor'
    },
    en: {
      unauthorized: 'Unauthorized',
      bookmarkRequired: 'Verse list is required',
      bookmarkError: 'Error checking bookmarks'
    }
  }
  return messages[locale as keyof typeof messages] || messages.ro
}

// POST - Check multiple verses for bookmarks
export async function POST(request: Request) {
  try {
    const url = new URL(request.url)
    const locale = url.searchParams.get('locale') || 'ro'
    const messages = getErrorMessages(locale)

    // Get token from authorization header
    const authHeader = request.headers.get('authorization')
    const token = authHeader?.replace('Bearer ', '')

    if (!token) {
      return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
    }

    // Verify token and get user
    const user = await getUserFromToken(token)
    if (!user) {
      return NextResponse.json({ error: messages.unauthorized }, { status: 401 })
    }

    // Parse request body
    const { verseIds } = await request.json()

    // Validate input
    if (!verseIds || !Array.isArray(verseIds)) {
      return NextResponse.json({ error: messages.bookmarkRequired }, { status: 400 })
    }

    // Get all bookmarks for these verses
    const bookmarks = await prisma.bookmark.findMany({
      where: {
        userId: user.id,
        verseId: {
          in: verseIds
        }
      }
    })

    // Create a map of verseId -> bookmark
    const bookmarkMap: Record<string, typeof bookmarks[number]> = {}
    bookmarks.forEach(bookmark => {
      bookmarkMap[bookmark.verseId] = bookmark
    })

    return NextResponse.json({
      bookmarks: bookmarkMap
    })

  } catch (error) {
    console.error('Verse bookmark bulk check error:', error)
    const url = new URL(request.url)
    const locale = url.searchParams.get('locale') || 'ro'
    const messages = getErrorMessages(locale)

    return NextResponse.json({ error: messages.bookmarkError }, { status: 500 })
  }
}
