import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import { prisma } from '@/lib/prisma'
import { revalidatePath } from 'next/cache'
import { deleteImageFileSafely, parseImageUrls } from '@/lib/image-cleanup'

export async function POST(req: NextRequest) {
  try {
    // Check authentication
    const session = await auth()
    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, error: 'Unauthorized' },
        { status: 401 }
      )
    }

    // Fetch notes with images before deleting for cleanup
    const notesWithImages = await prisma.note.findMany({
      where: { userId: session.user.id },
      select: { id: true, images: true },
    })

    // Delete all notes for the user (cascade will handle labels-note relationships)
    const result = await prisma.note.deleteMany({
      where: {
        userId: session.user.id
      }
    })

    // Clean up image files from disk (best-effort, don't block response)
    const imageCleanup = Promise.allSettled(
      notesWithImages.flatMap(note =>
        parseImageUrls(note.images).map(url => deleteImageFileSafely(url, note.id))
      )
    )

    // Delete all labels for the user
    await prisma.label.deleteMany({
      where: {
        userId: session.user.id
      }
    })

    // Delete all notebooks for the user
    await prisma.notebook.deleteMany({
      where: {
        userId: session.user.id
      }
    })

    // Revalidate paths
    revalidatePath('/')
    revalidatePath('/settings/data')

    // Await cleanup in background (don't block response)
    imageCleanup.catch(() => {})

    return NextResponse.json({
      success: true,
      deletedNotes: result.count
    })
  } catch (error) {
    console.error('Delete all error:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to delete notes' },
      { status: 500 }
    )
  }
}
