import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { auth } from '@/auth'
import { revalidatePath } from 'next/cache'

// PATCH /api/notebooks/[id] - Update a notebook
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await auth()
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  try {
    const { id } = await params
    const body = await request.json()
    const { name, icon, color, order } = body

    // Verify ownership
    const existing = await prisma.notebook.findUnique({
      where: { id },
      select: { userId: true }
    })

    if (!existing) {
      return NextResponse.json(
        { success: false, error: 'Notebook not found' },
        { status: 404 }
      )
    }

    if (existing.userId !== session.user.id) {
      return NextResponse.json(
        { success: false, error: 'Forbidden' },
        { status: 403 }
      )
    }

    // Build update data
    const updateData: any = {}
    if (name !== undefined) updateData.name = name.trim()
    if (icon !== undefined) updateData.icon = icon
    if (color !== undefined) updateData.color = color
    if (order !== undefined) updateData.order = order

    // Update notebook
    const notebook = await prisma.notebook.update({
      where: { id },
      data: updateData,
      include: {
        labels: true,
        _count: {
          select: { notes: true }
        }
      }
    })

    revalidatePath('/')

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

// DELETE /api/notebooks/[id] - Delete a notebook
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await auth()
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  try {
    const { id } = await params

    // Verify ownership and get notebook info
    const notebook = await prisma.notebook.findUnique({
      where: { id },
      select: {
        userId: true,
        name: true,
        _count: {
          select: { notes: true, labels: true }
        }
      }
    })

    if (!notebook) {
      return NextResponse.json(
        { success: false, error: 'Notebook not found' },
        { status: 404 }
      )
    }

    if (notebook.userId !== session.user.id) {
      return NextResponse.json(
        { success: false, error: 'Forbidden' },
        { status: 403 }
      )
    }

    // Delete notebook (cascade will handle labels and notes)
    await prisma.notebook.delete({
      where: { id }
    })

    revalidatePath('/')

    return NextResponse.json({
      success: true,
      message: `Notebook "${notebook.name}" deleted`,
      notesCount: notebook._count.notes,
      labelsCount: notebook._count.labels
    })
  } catch (error) {
    console.error('Error deleting notebook:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to delete notebook' },
      { status: 500 }
    )
  }
}
