import { createTRPCRouter, protectedProcedure } from "$lib/trpc/t";
import { z } from "zod";
import { UserController } from "./controller";
import { paginationModel } from "@pkg/logic/core/pagination.utils";
import { getError, Logger } from "$lib/core/logger";
import {
	createUserPayloadModel,
	updateUserInfoInputModel,
} from "../data/entities";
import { UserRoleMap } from "$lib/core/enums";
import { ERROR_CODES } from "$lib/core/error.codes";

export const userRouter = createTRPCRouter({
	getProfileInfo: protectedProcedure.query(async ({ ctx }) => {
		const controller = new UserController();
		const reqUserId = ctx?.user?.id ?? "";
		return await controller.getUserById(reqUserId);
	}),

	getAgentsPaginatedInfo: protectedProcedure
		.input(z.object({ info: paginationModel, fetchNext: z.boolean() }))
		.query(async ({ ctx, input }) => {
			const controller = new UserController();
			return await controller.getAgentsPaginatedInfo(
				ctx.user,
				input.info,
				input.fetchNext,
			);
		}),

	createUser: protectedProcedure
		.input(createUserPayloadModel)
		.mutation(async ({ input, ctx }) => {
			const controller = new UserController();
			if (ctx.user.role !== UserRoleMap.ADMIN) {
				return {
					error: getError({
						code: ERROR_CODES.PERMISSION_ERROR,
						message: "You are not authorized to create user",
						userHint: "You must be a manager to create an agent",
						detail: "Unauthorized to create agent",
						actionable: false,
					}),
				};
			}
			return controller.createUser(ctx.user.id ?? "", input, ctx.headers);
		}),

	updateUserInfo: protectedProcedure
		.input(updateUserInfoInputModel)
		.mutation(async ({ input, ctx }) => {
			const uc = new UserController();
			Logger.info({
				message: `Updating agent info ${input.username} (req:${ctx?.user?.username})`,
			});
			return await uc.updateUsersInfo(ctx?.user?.id ?? "", input);
		}),

	updateProfileInfo: protectedProcedure
		.input(updateUserInfoInputModel)
		.mutation(async ({ input, ctx }) => {
			const uc = new UserController();
			Logger.info({
				message: `Updating agent info ${input.username} (req:${ctx?.user?.username})`,
			});
			return await uc.updateProfileInfo(ctx?.user?.id ?? "", input);
		}),
});
