import { FastifyInstance } from "fastify" import { db } from "../db" import { projectTemplates } from "../db/schema" import { eq } from "drizzle-orm" import { z } from "zod" const ProjectTemplateSchema = z.object({ name: z.string().min(1), description: z.string().optional(), }) const ProjectTemplateUpdateSchema = ProjectTemplateSchema.partial() export default async function projectTemplateRoutes(fastify: FastifyInstance) { fastify.addHook("preHandler", async (request, reply) => { try { await request.jwtVerify() } catch (err) { return reply.code(401).send({ message: "Unauthorized" }) } const user = request.user as any if (user?.role !== "admin") { return reply.code(403).send({ message: "Admin privileges required" }) } }) fastify.get("/", async (request, reply) => { const results = await db .select() .from(projectTemplates) .orderBy(projectTemplates.name) return results }) fastify.get("/:id", async (request, reply) => { const { id } = request.params as { id: string } const [template] = await db .select() .from(projectTemplates) .where(eq(projectTemplates.id, id)) .limit(1) if (!template) { return reply.code(404).send({ message: "Project template not found" }) } return template }) fastify.post("/", async (request, reply) => { const body = ProjectTemplateSchema.parse(request.body) const [template] = await db .insert(projectTemplates) .values({ name: body.name, description: body.description, }) .returning() return reply.code(201).send(template) }) fastify.patch("/:id", async (request, reply) => { const { id } = request.params as { id: string } const body = ProjectTemplateUpdateSchema.parse(request.body) const [template] = await db .update(projectTemplates) .set(body) .where(eq(projectTemplates.id, id)) .returning() if (!template) { return reply.code(404).send({ message: "Project template not found" }) } return template }) fastify.delete("/:id", async (request, reply) => { const { id } = request.params as { id: string } const [template] = await db .delete(projectTemplates) .where(eq(projectTemplates.id, id)) .returning() if (!template) { return reply.code(404).send({ message: "Project template not found" }) } return reply.code(204).send() }) }