import { TRPCError } from "@trpc/server";
import type { AnnunciId } from "~/schemas/public/Annunci";
import type { UsersId } from "~/schemas/public/Users";
import { db } from "~/server/db";
import { withImages, withVideos } from "~/utils/kysely-helper";

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}`,
		});
	}
};
export const GetUserInterestsAnnunci = async (userId: UsersId) => {
	try {
		const interests = await GetUserInterests(userId);
		if (!interests || interests.length === 0) {
			return [];
		}
		const annunci = await db
			.selectFrom("annunci")
			.select((_eb) => [
				"annunci.id",
				"annunci.codice",
				"annunci.comune",
				"annunci.provincia",
				"annunci.prezzo",
				"annunci.consegna",
				"annunci.numero_camere",
				"annunci.mq",
				"annunci.tipo",
				"annunci.titolo_it",
				"annunci.titolo_en",
				"annunci.desc_en",
				"annunci.desc_it",
				"annunci.modificato_il",
				"annunci.stato",
				"annunci.external_videos",
				"annunci.media_updated_at",
				"annunci.homepage",
				"annunci.web",
				withImages(),
				withVideos(),
			])
			.where("web", "=", true)
			.where("stato", "!=", "Sospeso")
			.where("annunci.id", "in", interests)
			.execute();
		return annunci;
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore durante il recupero degli annunci: ${(e as Error).message}`,
		});
	}
};
