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

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 }
      )
    }

    // Parse form data
    const formData = await req.formData()
    const file = formData.get('file') as File

    if (!file) {
      return NextResponse.json(
        { success: false, error: 'No file provided' },
        { status: 400 }
      )
    }

    // Parse JSON file
    const text = await file.text()
    let importData: any

    try {
      importData = JSON.parse(text)
    } catch (error) {
      return NextResponse.json(
        { success: false, error: 'Invalid JSON file' },
        { status: 400 }
      )
    }

    // Validate import data structure
    if (!importData.data || !importData.data.notes) {
      return NextResponse.json(
        { success: false, error: 'Invalid import format' },
        { status: 400 }
      )
    }

    let importedNotes = 0
    let importedLabels = 0
    let importedNotebooks = 0

    // Import labels first
    if (importData.data.labels && Array.isArray(importData.data.labels)) {
      for (const label of importData.data.labels) {
        // Check if label already exists
        const existing = await prisma.label.findFirst({
          where: {
            userId: session.user.id,
            name: label.name
          }
        })

        if (!existing) {
          await prisma.label.create({
            data: {
              userId: session.user.id,
              name: label.name,
              color: label.color
            }
          })
          importedLabels++
        }
      }
    }

    // Import notebooks
    const notebookIdMap = new Map<string, string>()
    if (importData.data.notebooks && Array.isArray(importData.data.notebooks)) {
      for (const notebook of importData.data.notebooks) {
        // Check if notebook already exists
        const existing = await prisma.notebook.findFirst({
          where: {
            userId: session.user.id,
            name: notebook.name
          }
        })

        let newNotebookId
        if (!existing) {
          const created = await prisma.notebook.create({
            data: {
              userId: session.user.id,
              name: notebook.name,
              order: 0
            }
          })
          newNotebookId = created.id
          notebookIdMap.set(notebook.id, newNotebookId)
          importedNotebooks++
        } else {
          notebookIdMap.set(notebook.id, existing.id)
        }
      }
    }

    // Import notes
    if (importData.data.notes && Array.isArray(importData.data.notes)) {
      for (const note of importData.data.notes) {
        // Map notebook ID
        const mappedNotebookId = notebookIdMap.get(note.notebookId) || null

        // Get label IDs
        const labels = await prisma.label.findMany({
          where: {
            userId: session.user.id,
            name: {
              in: note.labels.map((l: any) => l.name)
            }
          }
        })

        // Create note
        await prisma.note.create({
          data: {
            userId: session.user.id,
            title: note.title || 'Untitled',
            content: note.content,
            isPinned: note.isPinned || false,
            notebookId: mappedNotebookId,
            labelRelations: {
              connect: labels.map(label => ({ id: label.id }))
            }
          }
        })
        importedNotes++
      }
    }

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

    return NextResponse.json({
      success: true,
      count: importedNotes,
      labels: importedLabels,
      notebooks: importedNotebooks
    })
  } catch (error) {
    console.error('Import error:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to import notes' },
      { status: 500 }
    )
  }
}
