import { z } from "zod";
import {
  adminProcedure,
  createTRPCRouter,
  protectedProcedure,
} from "~/server/api/trpc";
import {
  deleteChatHandler,
  getActiveInfos,
  getChatByUser,
  getChatByUserIdHandler,
  getChatInfo,
  getUserByChatHandler,
} from "~/server/controllers/chat.controller";
import {
  addChatEtichette,
  getChatEtichette,
  removeChatEtichette,
} from "~/server/controllers/etichette.controller";
import { zChatId, zEtichettaId, zUserId } from "~/server/utils/zod_types";
import { db } from "~/server/db";

export const chatRouter = createTRPCRouter({
  getSessionChats: protectedProcedure.query(async ({ ctx }) => {
    return await getChatByUser({
      userId: ctx.session.id,
    });
  }),

  getChatInfobyId: protectedProcedure
    .input(
      z.object({
        chatId: zChatId,
      }),
    )
    .query(async ({ input }) => {
      return await getChatInfo({ chatId: input.chatId });
    }),

  getActiveChats: adminProcedure.query(async ({ ctx }) => {
    return await getActiveInfos({ userId: ctx.session.id });
  }),
  deleteChat: adminProcedure
    .input(
      z.object({
        chatId: zChatId,
      }),
    )
    .mutation(async ({ input }) => {
      return await deleteChatHandler({ chatId: input.chatId });
    }),

  getUserInfosByChat: protectedProcedure
    .input(
      z.object({
        chatId: zChatId,
      }),
    )
    .query(async ({ input }) => {
      return await getUserByChatHandler({ chatId: input.chatId });
    }),
  getChatIdByUser: adminProcedure
    .input(z.object({ userId: zUserId }))
    .query(async ({ input }) => {
      return await getChatByUserIdHandler({ userId: input.userId });
    }),
  getChatEtichette: protectedProcedure
    .input(z.object({ chatId: zChatId }))
    .query(async ({ input }) => {
      return await getChatEtichette({
        db,
        chatid: input.chatId,
      });
    }),
  addEtichettaToChat: protectedProcedure
    .input(z.object({ chatId: zChatId, etichettaId: zEtichettaId }))
    .mutation(async ({ input }) => {
      return await addChatEtichette({
        db,
        chatid: input.chatId,
        etichettaid: input.etichettaId,
      });
    }),
  removeEtichettaFromChat: protectedProcedure
    .input(z.object({ chatId: zChatId, etichettaId: zEtichettaId }))
    .mutation(async ({ input }) => {
      return await removeChatEtichette({
        db,
        chatid: input.chatId,
        etichettaid: input.etichettaId,
      });
    }),
});
