import { type NextRequest } from "next/server"; import { prisma } from "@/lib/prisma"; import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api"; import { UpdateTemplateSchema } 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 template = await prisma.operationTemplate.findUnique({ where: { id }, include: { machine: true }, }); if (!template) throw new ApiError(404, "not_found", "Template not found"); return ok({ template }); } 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, UpdateTemplateSchema); const before = await prisma.operationTemplate.findUnique({ where: { id } }); if (!before) throw new ApiError(404, "not_found", "Template not found"); const updated = await prisma.operationTemplate.update({ where: { id }, data: { ...(body.name !== undefined ? { name: body.name } : {}), ...(body.machineId !== undefined ? { machineId: body.machineId } : {}), ...(body.defaultSettings !== undefined ? { defaultSettings: body.defaultSettings } : {}), ...(body.defaultInstructions !== undefined ? { defaultInstructions: body.defaultInstructions } : {}), ...(body.qcRequired !== undefined ? { qcRequired: body.qcRequired } : {}), ...(body.active !== undefined ? { active: body.active } : {}), }, }); await audit({ actorId: actor.id, action: "update", entity: "OperationTemplate", entityId: id, before, after: updated, ipAddress: clientIp(req), }); return ok({ template: 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.operationTemplate.findUnique({ where: { id } }); if (!before) throw new ApiError(404, "not_found", "Template not found"); const updated = await prisma.operationTemplate.update({ where: { id }, data: { active: false }, }); await audit({ actorId: actor.id, action: "deactivate", entity: "OperationTemplate", entityId: id, before, after: updated, ipAddress: clientIp(req), }); return ok({ ok: true }); } catch (err) { return errorResponse(err); } }