import { NextRequest, NextResponse } from 'next/server'; import { db } from '@/lib/db'; import { getCookieToken, getSessionUser } from '@/lib/auth'; import { invoiceIdSchema } from '@/lib/validation'; import { logActivity } from '@/lib/activity'; type FilterValue = 'all' | 'done' | 'review' | 'duplicates'; // ─── GET: List Invoices ─────────────────────────────────────────────────────── 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 }); } const { searchParams } = new URL(request.url); const filter = (searchParams.get('filter') || 'all') as FilterValue; // Build the where clause const where: Record = { userId: user.id }; switch (filter) { case 'done': where.status = 'done'; where.isDuplicate = false; break; case 'review': where.status = 'review'; break; case 'duplicates': where.isDuplicate = true; break; // 'all' uses the base where (userId only) } const invoices = await db.invoice.findMany({ where, orderBy: { createdAt: 'desc' }, }); return NextResponse.json({ invoices }); } catch (error) { console.error('[INVOICES_GET_ERROR]', error); return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ); } } // ─── DELETE: Remove Invoice ──────────────────────────────────────────────────── export async function DELETE(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 }); } const body = await request.json(); const parsed = invoiceIdSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( { error: parsed.error.issues[0].message }, { status: 400 } ); } // Verify ownership const invoice = await db.invoice.findUnique({ where: { id: parsed.data.id }, }); if (!invoice || invoice.userId !== user.id) { return NextResponse.json( { error: 'Invoice not found' }, { status: 404 } ); } await db.invoice.delete({ where: { id: parsed.data.id } }); logActivity(user.id, 'delete', 'Invoice deleted', `Removed invoice ${parsed.data.id}`); return NextResponse.json({ success: true }); } catch (error) { console.error('[INVOICES_DELETE_ERROR]', error); return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ); } }