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

// POST /api/notebooks/reorder - Reorder notebooks
export async function POST(request: NextRequest) {
  const session = await auth()
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  try {
    const body = await request.json()
    const { notebookIds } = body

    if (!Array.isArray(notebookIds)) {
      return NextResponse.json(
        { success: false, error: 'notebookIds must be an array' },
        { status: 400 }
      )
    }

    // Verify all notebooks belong to the user
    const notebooks = await prisma.notebook.findMany({
      where: {
        id: { in: notebookIds },
        userId: session.user.id
      },
      select: { id: true }
    })

    if (notebooks.length !== notebookIds.length) {
      return NextResponse.json(
        { success: false, error: 'One or more notebooks not found or unauthorized' },
        { status: 403 }
      )
    }

    // Update order for each notebook
    const updates = notebookIds.map((id, index) =>
      prisma.notebook.update({
        where: { id },
        data: { order: index }
      })
    )

    await prisma.$transaction(updates)

    revalidatePath('/')

    return NextResponse.json({
      success: true,
      message: 'Notebooks reordered successfully'
    })
  } catch (error) {
    return NextResponse.json(
      { success: false, error: 'Failed to reorder notebooks' },
      { status: 500 }
    )
  }
}
