import { type NextRequest } from "next/server"; import { prisma } from "@/lib/prisma"; import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api"; import { UpdateProjectSchema } from "@/lib/schemas"; import { audit } from "@/lib/audit"; import { clientIp } from "@/lib/request"; export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) { try { await requireRole("admin"); const { id } = await ctx.params; const project = await prisma.project.findUnique({ where: { id }, include: { assemblies: { orderBy: { code: "asc" }, include: { _count: { select: { parts: true } } }, }, fasteners: true, purchaseOrders: { orderBy: { createdAt: "desc" } }, }, }); if (!project) throw new ApiError(404, "not_found", "Project not found"); return ok({ project }); } catch (err) { return errorResponse(err); } } export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) { try { const actor = await requireRole("admin"); const { id } = await ctx.params; const body = await parseJson(req, UpdateProjectSchema); const before = await prisma.project.findUnique({ where: { id } }); if (!before) throw new ApiError(404, "not_found", "Project not found"); const updated = await prisma.project.update({ where: { id }, data: { ...(body.code !== undefined ? { code: body.code } : {}), ...(body.name !== undefined ? { name: body.name } : {}), ...(body.customerCode !== undefined ? { customerCode: body.customerCode } : {}), ...(body.dueDate !== undefined ? { dueDate: body.dueDate } : {}), ...(body.status !== undefined ? { status: body.status } : {}), ...(body.notes !== undefined ? { notes: body.notes } : {}), }, }); await audit({ actorId: actor.id, action: "update", entity: "Project", entityId: id, before, after: updated, ipAddress: clientIp(req), }); return ok({ project: updated }); } catch (err) { return errorResponse(err); } } export async function DELETE(req: NextRequest, ctx: { params: Promise<{ id: string }> }) { try { const actor = await requireRole("admin"); const { id } = await ctx.params; const before = await prisma.project.findUnique({ where: { id } }); if (!before) throw new ApiError(404, "not_found", "Project not found"); await prisma.project.delete({ where: { id } }); await audit({ actorId: actor.id, action: "delete", entity: "Project", entityId: id, before, ipAddress: clientIp(req), }); return ok({ ok: true }); } catch (err) { return errorResponse(err); } }