import { TRPCError } from "@trpc/server"; import type { ChatsChatid } from "~/schemas/public/Chats"; import type { EtichetteIdEtichetta } from "~/schemas/public/Etichette"; import type { Querier } from "~/server/db"; export const getAllEtichette = async ({ db }: { db: Querier }) => { return await db.selectFrom("etichette").selectAll().execute(); }; export const addEtichetta = async ({ db, title, color_hex, }: { db: Querier; title: string; color_hex: string; }) => { try { return await db .insertInto("etichette") .returning("id_etichetta") .values({ title, color_hex }) .execute(); } catch { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Errore aggiunta etichetta", }); } }; export const updateEtichetta = async ({ db, etichettaid, title, color_hex, }: { db: Querier; etichettaid: EtichetteIdEtichetta; title: string; color_hex: string; }) => { try { return await db .updateTable("etichette") .returning("id_etichetta") .set({ title, color_hex }) .where("id_etichetta", "=", etichettaid) .execute(); } catch { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Errore aggiornamento etichetta", }); } }; export const removeEtichetta = async ({ db, etichettaid, }: { db: Querier; etichettaid: EtichetteIdEtichetta; }) => { try { await db .deleteFrom("etichette") .where("id_etichetta", "=", etichettaid) .execute(); return "ok"; } catch { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Errore rimozione etichetta", }); } }; export const getChatEtichette = async ({ db, chatid, }: { db: Querier; chatid: ChatsChatid; }) => { try { return await db .selectFrom("etichette") .innerJoin( "chats_etichette", "etichette.id_etichetta", "chats_etichette.etichettaid", ) .where("chats_etichette.chatid", "=", chatid) .select([ "etichette.id_etichetta", "etichette.title", "etichette.color_hex", ]) .execute(); } catch { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Errore recupero etichette", }); } }; export const addChatEtichette = async ({ db, chatid, etichettaid, }: { db: Querier; chatid: ChatsChatid; etichettaid: EtichetteIdEtichetta; }) => { try { return await db .insertInto("chats_etichette") .returning("chatid") .values({ chatid, etichettaid }) .onConflict((oc) => oc.columns(["chatid", "etichettaid"]).doNothing()) .execute(); } catch { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Errore aggiunta etichetta", }); } }; export const removeChatEtichette = async ({ db, chatid, etichettaid, }: { db: Querier; chatid: ChatsChatid; etichettaid: EtichetteIdEtichetta; }) => { try { await db .deleteFrom("chats_etichette") .where("chatid", "=", chatid) .where("etichettaid", "=", etichettaid) .execute(); return "ok"; } catch { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Errore rimozione etichetta", }); } };