import { NextRequest, NextResponse } from 'next/server' import { auth } from '@/auth' import { prisma } from '@/lib/prisma' export async function GET(req: NextRequest) { try { const session = await auth() if (!session?.user?.id) { return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 }) } const userId = session.user.id const [allNotes, labels, notebooks] = await Promise.all([ prisma.note.findMany({ where: { userId }, orderBy: { createdAt: 'asc' }, }), prisma.label.findMany({ where: { userId }, include: { notes: { select: { id: true } } }, }), prisma.notebook.findMany({ where: { userId }, include: { notes: { select: { id: true } } }, }), ]) const noteLabelMap = new Map() for (const label of labels) { for (const note of label.notes) { const arr = noteLabelMap.get(note.id) || [] arr.push(label.id) noteLabelMap.set(note.id, arr) } } const exportData = { version: '2.0.0', exportDate: new Date().toISOString(), user: { id: userId, email: session.user.email ?? '', name: session.user.name ?? '', }, data: { notebooks: notebooks.map(nb => ({ id: nb.id, name: nb.name, icon: nb.icon, color: nb.color, order: nb.order, parentId: nb.parentId, trashedAt: nb.trashedAt?.toISOString() ?? null, createdAt: nb.createdAt.toISOString(), updatedAt: nb.updatedAt.toISOString(), noteIds: nb.notes.map(n => n.id), })), labels: labels.map(lb => ({ id: lb.id, name: lb.name, color: lb.color, notebookId: lb.notebookId, type: lb.type, createdAt: lb.createdAt.toISOString(), updatedAt: lb.updatedAt.toISOString(), noteIds: lb.notes.map(n => n.id), })), notes: allNotes.map(n => ({ id: n.id, title: n.title, content: n.content, color: n.color, isPinned: n.isPinned, isArchived: n.isArchived, type: n.type, order: n.order, isMarkdown: n.isMarkdown, size: n.size, autoGenerated: n.autoGenerated, historyEnabled: n.historyEnabled, checkItems: n.checkItems, images: n.images, links: n.links, trashedAt: n.trashedAt?.toISOString() ?? null, notebookId: n.notebookId, createdAt: n.createdAt.toISOString(), updatedAt: n.updatedAt.toISOString(), contentUpdatedAt: n.contentUpdatedAt?.toISOString() ?? null, labelIds: noteLabelMap.get(n.id) || [], })), }, } 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 }) } }