import { NextRequest, NextResponse } from 'next/server'; import { invoiceSchema, invoiceTableFiltersSchema } from 'mvpmasters-shared'; import prisma from 'src/lib/prisma'; import { auth } from 'src/lib/firebase-admin'; // Helper function to get userId from Authorization header async function getUserId(request: NextRequest) { const authHeader = request.headers.get('Authorization'); if (!authHeader?.startsWith('Bearer ')) { return null; } try { const token = authHeader.split('Bearer ')[1]; const decodedToken = await auth.verifyIdToken(token); return decodedToken.uid; } catch (error) { return null; } } export async function GET(request: NextRequest) { try { const userId = await getUserId(request); if (!userId) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const searchParams = request.nextUrl.searchParams; const filters = { name: searchParams.get('name') || '', service: searchParams.getAll('service'), status: searchParams.get('status') || '', startDate: searchParams.get('startDate') ? new Date(searchParams.get('startDate')!) : null, endDate: searchParams.get('endDate') ? new Date(searchParams.get('endDate')!) : null, }; // Validate filters const validatedFilters = invoiceTableFiltersSchema.parse(filters); const invoices = await prisma.invoice.findMany({ where: { userId, status: validatedFilters.status ? { equals: validatedFilters.status } : undefined, createDate: { gte: validatedFilters.startDate, lte: validatedFilters.endDate, }, items: validatedFilters.service.length > 0 ? { some: { service: { id: { in: validatedFilters.service } } } } : undefined, }, include: { items: { include: { service: true, }, }, invoiceFrom: true, invoiceTo: true, }, }); return NextResponse.json(invoices); } catch (error) { return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); } } export async function POST(request: NextRequest) { try { const userId = await getUserId(request); if (!userId) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const body = await request.json(); const validatedData = invoiceSchema.parse(body); const invoice = await prisma.invoice.create({ data: { ...validatedData, userId, items: { create: validatedData.items, }, }, include: { items: { include: { service: true, }, }, invoiceFrom: true, invoiceTo: true, }, }); return NextResponse.json(invoice, { status: 201 }); } catch (error) { return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); } }