import { NextRequest, NextResponse } from 'next/server'; import { getCoilReceipts } from '@/services/coil-activity'; import { getQuestSession, getActiveCompany } from '@/lib/permissions'; import { cachedQuery } from '@/lib/cache'; export const dynamic = 'force-dynamic'; export async function GET(request: NextRequest) { const session = await getQuestSession(); const activeCompany = await getActiveCompany(); if (!session || !activeCompany) { return NextResponse.json({ error: 'No active company' }, { status: 401 }); } const { searchParams } = new URL(request.url); const startDate = searchParams.get('startDate'); const endDate = searchParams.get('endDate'); if (!startDate || !endDate) { return NextResponse.json( { error: 'startDate and endDate query parameters are required' }, { status: 400 } ); } const start = new Date(startDate); const end = new Date(endDate); if (isNaN(start.getTime()) || isNaN(end.getTime())) { return NextResponse.json({ error: 'Invalid date format' }, { status: 400 }); } if (end < start) { return NextResponse.json( { error: 'endDate must be after startDate' }, { status: 400 } ); } const diffDays = Math.ceil( (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24) ); if (diffDays > 31) { return NextResponse.json( { error: 'Date range cannot exceed 31 days' }, { status: 400 } ); } const custId = activeCompany.epicor_cust_id; try { const data = await cachedQuery( { key: `coil:${custId}:receipts:${startDate}:${endDate}`, ttlSeconds: 300 }, () => getCoilReceipts(custId, startDate, endDate) ); return NextResponse.json(data); } catch (err) { const message = err instanceof Error ? err.message : String(err); let details = ''; if (err && typeof err === 'object' && 'originalError' in err) { const originalError = (err as { originalError: unknown }).originalError; details = originalError instanceof Error ? originalError.message : String(originalError); } console.error('Coil receipts error:', err); return NextResponse.json({ error: message, details }, { status: 500 }); } }