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

export const runtime = 'nodejs'

export async function GET(request: Request) {
  try {
    const authHeader = request.headers.get('authorization')
    const token = authHeader?.replace('Bearer ', '')

    if (!token) {
      return NextResponse.json({ error: 'Token de autentificare necesar' }, { status: 401 })
    }

    const user = await getUserFromToken(token)
    if (!user) {
      return NextResponse.json({ error: 'Token invalid' }, { status: 401 })
    }

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

    return NextResponse.json({ bookmarks })
  } catch (error) {
    console.error('Bookmarks fetch error:', error)
    return NextResponse.json({ error: 'Eroare de server' }, { status: 500 })
  }
}

export async function POST(request: Request) {
  try {
    const authHeader = request.headers.get('authorization')
    const token = authHeader?.replace('Bearer ', '')

    if (!token) {
      return NextResponse.json({ error: 'Token de autentificare necesar' }, { status: 401 })
    }

    const user = await getUserFromToken(token)
    if (!user) {
      return NextResponse.json({ error: 'Token invalid' }, { status: 401 })
    }

    const { verseId, note, color } = await request.json()

    if (!verseId) {
      return NextResponse.json({ error: 'ID-ul versului este obligatoriu' }, { status: 400 })
    }

    // Check if bookmark already exists
    const existing = await prisma.bookmark.findUnique({
      where: {
        userId_verseId: {
          userId: user.id,
          verseId
        }
      }
    })

    if (existing) {
      return NextResponse.json({ error: 'Acest verset este deja marcat' }, { status: 409 })
    }

    const bookmark = await prisma.bookmark.create({
      data: {
        userId: user.id,
        verseId,
        note,
        color: color || '#FFD700'
      },
      include: {
        verse: {
          include: {
            chapter: {
              include: {
                book: true
              }
            }
          }
        }
      }
    })

    return NextResponse.json({ bookmark })
  } catch (error) {
    console.error('Bookmark creation error:', error)
    return NextResponse.json({ error: 'Eroare de server' }, { status: 500 })
  }
}
