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

// PUT /api/highlights/[id]?locale=en - Update highlight
// DELETE /api/highlights/[id]?locale=en - Delete highlight
export async function PUT(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  const params = await context.params
  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 { color, note, tags } = body

    // Verify ownership
    const existingHighlight = await prisma.highlight.findUnique({
      where: { id: params.id }
    })

    if (!existingHighlight || existingHighlight.userId !== decoded.userId) {
      return NextResponse.json({ success: false, error: 'Highlight not found' }, { status: 404 })
    }

    const highlight = await prisma.highlight.update({
      where: { id: params.id },
      data: {
        ...(color && { color }),
        ...(note !== undefined && { note }),
        ...(tags && { tags })
      }
    })

    return NextResponse.json({ success: true, highlight })
  } catch (error) {
    console.error('Error updating highlight:', error)
    return NextResponse.json({ success: false, error: 'Failed to update highlight' }, { status: 500 })
  }
}

export async function DELETE(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  const params = await context.params
  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 })
    }

    // Verify ownership
    const existingHighlight = await prisma.highlight.findUnique({
      where: { id: params.id }
    })

    if (!existingHighlight || existingHighlight.userId !== decoded.userId) {
      return NextResponse.json({ success: false, error: 'Highlight not found' }, { status: 404 })
    }

    await prisma.highlight.delete({
      where: { id: params.id }
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error deleting highlight:', error)
    return NextResponse.json({ success: false, error: 'Failed to delete highlight' }, { status: 500 })
  }
}
