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

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

	getUsers: adminProcedure.query(async () => {
		return await db
			.selectFrom("users")
			.selectAll()
			.orderBy("id", "desc")
			.execute();
	}),
	getAdmins: adminProcedure.query(async () => {
		return await db
			.selectFrom("users")
			.selectAll()
			.where("isAdmin", "=", true)
			.orderBy("id", "desc")
			.execute();
	}),
	getClientProfilo: protectedProcedure
		.input(
			z.object({
				userId: zUserId,
			}),
		)
		.query(async ({ input }) => {
			return getClientProfilo({
				db,
				userId: input.userId,
			});
		}),
	blockUser: adminProcedure
		.input(
			z.object({
				id: zUserId,
			}),
		)
		.mutation(async ({ input }) => {
			return await blockUserHandler(input.id);
		}),
	deleteUser: adminProcedure
		.input(
			z.object({
				id: zUserId,
			}),
		)
		.mutation(async ({ input }) => {
			return await deleteUserHandler(input.id);
		}),
	editUser: protectedProcedure
		.input(
			z.object({
				id: zUserId,
				data: z.custom<UsersUpdate>(),
			}),
		)
		.mutation(async ({ input }) => {
			return await editAccountHandler({ ...input });
		}),
	editUserAnagrafica: protectedProcedure
		.input(
			z.object({
				userId: zUserId,
				data: z.custom<UsersAnagraficaUpdate>(),
			}),
		)
		.mutation(async ({ input }) => {
			return await editAnagraficaHandler({ ...input });
		}),
	getActiveUsersWithoutChat: adminProcedure.query(async () => {
		return await getActiveUserWithoutChatHandler({ db });
	}),

	getUsersWChatInfo: adminProcedure.query(async () => {
		return await getUsersWithChatInfoHandler();
	}),
	genIntestazione: adminProcedure
		.input(
			z.object({
				userId: zUserId,
			}),
		)
		.mutation(async ({ input }) => {
			return await genUserIntestazione(input.userId);
		}),
});
