import { TRPCError } from "@trpc/server";
import z from "zod/v4";
import { env } from "~/env";
import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
import { db } from "~/server/db";
import {
	AddIntrest,
	GetUserInterests,
	GetUserInterestsAnnunci,
	HasUserInterest,
	RemoveInterest,
} from "~/server/services/interests.service";
import { NewMail } from "~/server/services/mailer";
import { findUser_byId_MINI } from "~/server/services/user.service";
import { zAnnuncioId, zUserId } from "~/server/utils/zod_types";

export const intrestsRouter = createTRPCRouter({
	addIntrest: protectedProcedure
		.input(
			z.object({
				annuncioId: zAnnuncioId,
				/**Optional */
				userId: zUserId.optional(),
			}),
		)
		.mutation(async ({ ctx, input }) => {
			const userId = input.userId || ctx.session.id;
			await AddIntrest({
				annuncioId: input.annuncioId,
				userId,
			});
			const annuncio = await db
				.selectFrom("annunci")
				.select(["id", "codice", "titolo_it"])
				.where("id", "=", input.annuncioId)
				.executeTakeFirst();
			if (!annuncio) {
				throw new TRPCError({
					code: "NOT_FOUND",
					message: "Annuncio not found",
				});
			}
			const user = await findUser_byId_MINI({
				userId,
			});
			if (!user) {
				throw new TRPCError({
					code: "NOT_FOUND",
					message: "User not found",
				});
			}
			await NewMail({
				template: {
					mailType: "generic",
					props: {
						link: {
							href: `${env.BASE_URL}/area-riservata/admin/user-view/ricerca/${userId}`,
							label: "Visualizza utente",
						},
						testo: `L'utente ${user.username} (${user.email}) ha mostrato interesse per l'annuncio "${annuncio.titolo_it}" (Codice: ${annuncio.codice}).`,
						title: "Nuovo interesse per un annuncio",
					},
				},
				mail: {
					subject: "Utente interessato ad un annuncio",
					to: "web@infoalloggi.it",
				},
				userId,
			});
			return { success: true };
		}),
	getUserInterests: protectedProcedure
		.input(
			z.object({
				userId: zUserId.optional(),
			}),
		)
		.query(async ({ input, ctx }) => {
			return await GetUserInterests(input.userId || ctx.session.id);
		}),
	getUserInterestsAnnunci: protectedProcedure
		.input(
			z.object({
				userId: zUserId.optional(),
			}),
		)
		.query(async ({ input, ctx }) => {
			return await GetUserInterestsAnnunci(input.userId || ctx.session.id);
		}),
	hasUserInterest: protectedProcedure
		.input(
			z.object({
				annuncioId: zAnnuncioId,
				userId: zUserId.optional(),
			}),
		)
		.query(async ({ ctx, input }) => {
			return await HasUserInterest({
				annuncioId: input.annuncioId,
				userId: input.userId || ctx.session.id,
			});
		}),
	removeIntrest: protectedProcedure
		.input(
			z.object({
				annuncioId: zAnnuncioId,
				userId: zUserId.optional(),
			}),
		)
		.mutation(async ({ ctx, input }) => {
			return await RemoveInterest({
				annuncioId: input.annuncioId,
				userId: input.userId || ctx.session.id,
			});
		}),
});
