import { type NextRequest } from "next/server"; import { prisma } from "@/lib/prisma"; import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api"; import { UpdateAssemblySchema } 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 assembly = await prisma.assembly.findUnique({ where: { id }, include: { project: { select: { id: true, code: true, name: true } }, parts: { orderBy: { code: "asc" } }, }, }); if (!assembly) throw new ApiError(404, "not_found", "Assembly not found"); return ok({ assembly }); } 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, UpdateAssemblySchema); const before = await prisma.assembly.findUnique({ where: { id } }); if (!before) throw new ApiError(404, "not_found", "Assembly not found"); const updated = await prisma.assembly.update({ where: { id }, data: { ...(body.code !== undefined ? { code: body.code } : {}), ...(body.name !== undefined ? { name: body.name } : {}), ...(body.qty !== undefined ? { qty: body.qty } : {}), ...(body.notes !== undefined ? { notes: body.notes } : {}), ...(body.stepFileId !== undefined ? { stepFileId: body.stepFileId } : {}), ...(body.drawingFileId !== undefined ? { drawingFileId: body.drawingFileId } : {}), ...(body.cutFileId !== undefined ? { cutFileId: body.cutFileId } : {}), }, }); await audit({ actorId: actor.id, action: "update", entity: "Assembly", entityId: id, before, after: updated, ipAddress: clientIp(req), }); return ok({ assembly: 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.assembly.findUnique({ where: { id } }); if (!before) throw new ApiError(404, "not_found", "Assembly not found"); await prisma.assembly.delete({ where: { id } }); await audit({ actorId: actor.id, action: "delete", entity: "Assembly", entityId: id, before, ipAddress: clientIp(req), }); return ok({ ok: true }); } catch (err) { return errorResponse(err); } }