import { TRPCError } from "@trpc/server"; import { z } from "zod/v4"; import { adminProcedure, createTRPCRouter } from "~/server/api/trpc"; import { addEtichetta, getAllEtichette, removeEtichetta, updateEtichetta, } from "~/server/controllers/etichette.controller"; import { db } from "~/server/db"; import { zEtichettaId, zUserId } from "~/server/utils/zod_types"; export const etichetteRouter = createTRPCRouter({ addEtichetta: adminProcedure .input( z.object({ color_hex: z.string().max(7), title: z.string(), }), ) .mutation(async ({ input }) => { return await addEtichetta({ color_hex: input.color_hex, db, title: input.title, }); }), getAllEtichette: adminProcedure.query(async () => { return await getAllEtichette({ db }); }), removeEtichetta: adminProcedure .input(z.object({ id_etichetta: zEtichettaId })) .mutation(async ({ input }) => { return await removeEtichetta({ db, etichettaid: input.id_etichetta, }); }), updateEtichetta: adminProcedure .input( z.object({ color_hex: z.string().max(7), id_etichetta: zEtichettaId, title: z.string(), }), ) .mutation(async ({ input }) => { return await updateEtichetta({ color_hex: input.color_hex, db, etichettaid: input.id_etichetta, title: input.title, }); }), addUserEtichetta: adminProcedure .input( z.object({ userId: zUserId, etichettaId: zEtichettaId, }), ) .mutation(async ({ input }) => { try { await db .insertInto("user_etichette") .values({ etichettaId: input.etichettaId, userId: input.userId, }) .execute(); } catch (error) { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: `Errore aggiunta etichetta all'utente: ${error instanceof Error ? error.message : "Errore sconosciuto"}`, }); } }), removeUserEtichetta: adminProcedure .input( z.object({ userId: zUserId, etichettaId: zEtichettaId, }), ) .mutation(async ({ input }) => { try { await db .deleteFrom("user_etichette") .where("etichettaId", "=", input.etichettaId) .where("userId", "=", input.userId) .execute(); } catch (error) { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: `Errore rimozione etichetta all'utente: ${error instanceof Error ? error.message : "Errore sconosciuto"}`, }); } return "ok"; }), });