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: 'Informațiile bookmark-ului sunt obligatorii',
      bookmarkError: 'Eroare la verificarea bookmark-ului'
    },
    en: {
      unauthorized: 'Unauthorized',
      bookmarkRequired: 'Bookmark information is required',
      bookmarkError: 'Error checking bookmark'
    }
  }
  return messages[locale as keyof typeof messages] || messages.ro
}

// GET - Check if chapter is bookmarked
export async function GET(request: Request) {
  try {
    const url = new URL(request.url)
    const locale = url.searchParams.get('locale') || 'ro'
    const bookId = url.searchParams.get('bookId')
    const chapterNum = parseInt(url.searchParams.get('chapterNum') || '0')
    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 })
    }

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

    // Check if bookmark exists
    const bookmark = await prisma.chapterBookmark.findUnique({
      where: {
        userId_bookId_chapterNum: {
          userId: user.id,
          bookId: bookId,
          chapterNum: chapterNum
        }
      }
    })

    return NextResponse.json({
      isBookmarked: !!bookmark,
      bookmark: bookmark || null
    })

  } catch (error) {
    console.error('Bookmark 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 })
  }
}