import { NextRequest, NextResponse } from 'next/server'; import { db } from '@/lib/db'; import { getCookieToken, getSessionUser } from '@/lib/auth'; export async function GET(request: NextRequest) { try { const token = getCookieToken(request); if (!token) { return NextResponse.json({ error: 'Not authenticated' }, { status: 401 }); } const user = await getSessionUser(token); if (!user) { return NextResponse.json({ error: 'Not authenticated' }, { status: 401 }); } // Free plan users cannot export JSON if (user.plan === 'free') { return NextResponse.json( { error: 'JSON export is available on Basic, Pro, and Enterprise plans. Please upgrade your plan.' }, { status: 403 } ); } const invoices = await db.invoice.findMany({ where: { userId: user.id }, orderBy: { createdAt: 'desc' }, }); const jsonData = invoices.map((inv) => ({ id: inv.id, filename: inv.filename, vendor: inv.vendor, invoiceNumber: inv.invNumber, invoiceDate: inv.invDate, dueDate: inv.dueDate, subtotal: inv.amount, vatAmount: inv.vatAmount, total: inv.total, currency: inv.currency, status: inv.status, isDuplicate: inv.isDuplicate, confidence: inv.confidence, rawJson: inv.rawJson ? JSON.parse(inv.rawJson) : null, createdAt: inv.createdAt, updatedAt: inv.updatedAt, })); const timestamp = new Date().toISOString().split('T')[0]; return new NextResponse(JSON.stringify(jsonData, null, 2), { status: 200, headers: { 'Content-Type': 'application/json; charset=utf-8', 'Content-Disposition': `attachment; filename="invoices-${timestamp}.json"`, }, }); } catch (error) { console.error('[EXPORT_JSON_ERROR]', error); return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ); } }