import { z } from "zod";
import {
  adminProcedure,
  createTRPCRouter,
  protectedProcedure,
  publicProcedure,
} from "~/server/api/trpc";
import {
  blockUserHandler as blockUserHandler,
  deleteUserHandler,
  editAccountHandler,
  editAnagraficaHandler,
  getActiveUserWithoutChatHandler,
  getUserHandler,
  getUsersWithChatInfoHandler,
} from "~/server/controllers/user.controller";
import { zUserId } from "~/server/utils/zod_types";
import { getUserWithAnagraficaHandler } from "~/server/services/user.service";
import { db } from "~/server/db";
import type { UsersAnagraficaUpdate } from "~/schemas/public/UsersAnagrafica";

export const usersRouter = createTRPCRouter({
  getUser: protectedProcedure
    .input(
      z.object({
        id: zUserId,
      }),
    )
    .query(async ({ input }) => {
      return await getUserHandler({ db, id: input.id });
    }),
  getClientProfilo: protectedProcedure
    .input(
      z.object({
        id: zUserId.optional(),
      }),
    )
    .query(async ({ ctx, input }) => {
      const userId = input.id || ctx.session.id;

      return getUserWithAnagraficaHandler({
        db,
        userId: userId,
      });
    }),

  getUsers: adminProcedure.query(async () => {
    const query = await db
      .selectFrom("users")
      .selectAll()
      .orderBy("id", "desc")
      .execute();

    return query;
  }),
  deleteUser: adminProcedure
    .input(
      z.object({
        id: zUserId,
      }),
    )
    .mutation(async ({ ctx, input }) => {
      return await deleteUserHandler({ ctx, id: input.id });
    }),
  blockUser: adminProcedure
    .input(
      z.object({
        id: zUserId,
      }),
    )
    .mutation(async ({ ctx, input }) => {
      return await blockUserHandler({ ctx, id: input.id });
    }),
  editUser: protectedProcedure
    .input(
      z.object({
        id: zUserId,
        nome: z.string(),
        cognome: z.string(),
        telefono: z.string(),
        email: z.string().email(),
        isAdmin: z.boolean().optional(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      return await editAccountHandler({ ctx, input });
    }),
  editUserAnagrafica: protectedProcedure
    .input(z.custom<UsersAnagraficaUpdate>())
    .mutation(async ({ input }) => {
      return await editAnagraficaHandler({ input });
    }),
  getActiveUsersWithoutChat: adminProcedure.query(async () => {
    return await getActiveUserWithoutChatHandler({ db });
  }),
  getUsersWChatInfo: publicProcedure.query(async () => {
    return await getUsersWithChatInfoHandler({ db });
  }),
});
