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',
      bookmarkError: 'Eroare la încărcarea bookmark-urilor'
    },
    en: {
      unauthorized: 'Unauthorized',
      bookmarkError: 'Error loading bookmarks'
    }
  }
  return messages[locale as keyof typeof messages] || messages.ro
}

// GET - Get all user's bookmarks (both chapter and verse)
export async function GET(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 })
    }

    // Get chapter bookmarks
    const chapterBookmarks = await prisma.chapterBookmark.findMany({
      where: {
        userId: user.id
      },
      include: {
        book: {
          include: {
            version: true
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    })

    // Get verse bookmarks
    const verseBookmarks = await prisma.bookmark.findMany({
      where: {
        userId: user.id
      },
      include: {
        verse: {
          include: {
            chapter: {
              include: {
                book: {
                  include: {
                    version: true
                  }
                }
              }
            }
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    })

    // Transform the data for easier frontend consumption
    const transformedChapterBookmarks = chapterBookmarks.map(bookmark => ({
      id: bookmark.id,
      type: 'chapter' as const,
      title: `${bookmark.book.name} ${bookmark.chapterNum}`,
      subtitle: bookmark.book.version.name,
      note: bookmark.note,
      createdAt: bookmark.createdAt,
      navigation: {
        bookId: bookmark.bookId,
        chapterNum: bookmark.chapterNum
      },
      book: bookmark.book
    }))

    const transformedVerseBookmarks = verseBookmarks.map(bookmark => ({
      id: bookmark.id,
      type: 'verse' as const,
      title: `${bookmark.verse.chapter.book.name} ${bookmark.verse.chapter.chapterNum}:${bookmark.verse.verseNum}`,
      subtitle: bookmark.verse.chapter.book.version.name,
      note: bookmark.note,
      createdAt: bookmark.createdAt,
      color: bookmark.color,
      text: bookmark.verse.text.substring(0, 100) + (bookmark.verse.text.length > 100 ? '...' : ''),
      navigation: {
        bookId: bookmark.verse.chapter.bookId,
        chapterNum: bookmark.verse.chapter.chapterNum,
        verseNum: bookmark.verse.verseNum
      },
      verse: bookmark.verse
    }))

    // Combine and sort by creation date
    const allBookmarks = [...transformedChapterBookmarks, ...transformedVerseBookmarks]
      .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())

    return NextResponse.json({
      bookmarks: allBookmarks,
      stats: {
        total: allBookmarks.length,
        chapters: chapterBookmarks.length,
        verses: verseBookmarks.length
      }
    })

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