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

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

    // Fetch all notes with related data
    const notes = await prisma.note.findMany({
      where: {
        userId: session.user.id,
        trashedAt: null
      },
      include: {
        labelRelations: {
          select: {
            id: true,
            name: true
          }
        },
        notebook: {
          select: {
            id: true,
            name: true
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    })

    // Fetch labels separately
    const labels = await prisma.label.findMany({
      where: {
        userId: session.user.id
      },
      include: {
        notes: {
          select: {
            id: true
          }
        }
      }
    })

    // Fetch notebooks
    const notebooks = await prisma.notebook.findMany({
      where: {
        userId: session.user.id
      },
      include: {
        notes: {
          select: {
            id: true
          }
        }
      }
    })

    // Create export object
    const exportData = {
      version: '1.0.0',
      exportDate: new Date().toISOString(),
      user: {
        id: session.user.id,
        email: session.user.email,
        name: session.user.name
      },
      data: {
        labels: labels.map(label => ({
          id: label.id,
          name: label.name,
          color: label.color,
          noteCount: label.notes.length
        })),
        notebooks: notebooks.map(notebook => ({
          id: notebook.id,
          name: notebook.name,
          noteCount: notebook.notes.length
        })),
        notes: notes.map(note => ({
          id: note.id,
          title: note.title,
          content: note.content,
          createdAt: note.createdAt,
          updatedAt: note.updatedAt,
          isPinned: note.isPinned,
          notebookId: note.notebookId,
          labelRelations: note.labelRelations.map(label => ({
            id: label.id,
            name: label.name
          }))
        }))
      }
    }

    // Return as JSON file
    const jsonString = JSON.stringify(exportData, null, 2)
    return new NextResponse(jsonString, {
      headers: {
        'Content-Type': 'application/json',
        'Content-Disposition': `attachment; filename="memento-export-${new Date().toISOString().split('T')[0]}.json"`
      }
    })
  } catch (error) {
    console.error('Export error:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to export notes' },
      { status: 500 }
    )
  }
}
