import { TRPCError } from "@trpc/server";
import type { AnnunciId } from "~/schemas/public/Annunci";
import type { UsersId } from "~/schemas/public/Users";
import { db } from "~/server/db";

export const AddIntrest = async ({
	annuncioId,
	userId,
}: {
	annuncioId: AnnunciId;
	userId: UsersId;
}) => {
	try {
		await db
			.insertInto("servizio_interessi")
			.values({
				annuncioId,
				userId,
			})
			.onConflict((oc) => oc.columns(["annuncioId", "userId"]).doNothing())
			.execute();
		return { success: true };
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore durante l'aggiunta dell'interesse: ${(e as Error).message}`,
		});
	}
};

export const RemoveInterest = async ({
	annuncioId,
	userId,
}: {
	annuncioId: AnnunciId;
	userId: UsersId;
}) => {
	try {
		await db
			.deleteFrom("servizio_interessi")
			.where("annuncioId", "=", annuncioId)
			.where("userId", "=", userId)
			.execute();

		return { success: true };
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore durante la rimozione dell'interesse: ${(e as Error).message}`,
		});
	}
};

export const HasUserInterest = async ({
	annuncioId,
	userId,
}: {
	annuncioId: AnnunciId;
	userId: UsersId;
}) => {
	try {
		const interest = await db
			.selectFrom("servizio_interessi")
			.where("annuncioId", "=", annuncioId)
			.where("userId", "=", userId)
			.selectAll()
			.executeTakeFirst();

		return interest !== undefined;
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore durante il controllo dell'interesse: ${(e as Error).message}`,
		});
	}
};

export const GetUserInterests = async (userId: UsersId) => {
	try {
		return (
			await db
				.selectFrom("servizio_interessi")
				.where("userId", "=", userId)
				.select("annuncioId")
				.execute()
		).map((interest) => interest.annuncioId);
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore durante il recupero degli interessi: ${(e as Error).message}`,
		});
	}
};
