import type { NextApiRequest, NextApiResponse } from 'next' import { prisma } from '@/lib/prisma' import { requireAuth, logAction, generateRef } from '@/lib/auth' export default async function handler(req: NextApiRequest, res: NextApiResponse) { const user = await requireAuth(req, res) if (!user) return if (req.method === 'GET') { const shipments = await prisma.shipment.findMany({ include: { items: { orderBy: { order: 'asc' } }, _count: { select: { escapes: true } } }, orderBy: { createdAt: 'desc' }, }) return res.json({ data: shipments }) } if (req.method === 'POST') { const { product, batch, client, clientEmail, shippedAt, items } = req.body if (!product || !batch || !client || !shippedAt) { return res.status(400).json({ error: 'product, batch, client, shippedAt required' }) } const count = await prisma.shipment.count() const ref = generateRef('REL', count) const shipment = await prisma.shipment.create({ data: { ref, product, batch, client, clientEmail, shippedAt: new Date(shippedAt), createdById: user.id, items: { create: (items || []).map((it: any, i: number) => ({ label: it.label, type: it.type || 'OTHER', included: it.included !== false, order: i, })) } }, include: { items: { orderBy: { order: 'asc' } } }, }) await logAction(user.id, 'CREATE', 'Shipment', shipment.id, null, { ref, product, batch }) return res.status(201).json({ data: shipment }) } res.status(405).end() }