import { TRPCError } from "@trpc/server";
import type { Banners, BannersIdbanner } from "~/schemas/public/Banners";
import type { Querier } from "~/server/db";

export const getBanner = async ({
	db,
	area_riservata,
}: {
	db: Querier;
	area_riservata: boolean;
}) => {
	try {
		let query = db
			.selectFrom("banners")
			.selectAll()
			.where("banners.is_active", "=", true);
		if (area_riservata) {
			query = query.where("banners.show_private", "=", true);
		} else {
			query = query.where("banners.show_public", "=", true);
		}
		return await query.execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore nel recupero dei dati: ${(e as Error).message}`,
		});
	}
};

export const getAllBanners = async ({ db }: { db: Querier }) => {
	try {
		return await db.selectFrom("banners").selectAll().execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore nel recupero dei dati: ${(e as Error).message}`,
		});
	}
};

export const addBanner = async ({
	db,
	input,
}: {
	db: Querier;
	input: Banners;
}) => {
	try {
		return await db
			.insertInto("banners")
			.values({
				...input,
				idbanner: input.idbanner,
			})
			.returning("banners.idbanner")
			.execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore aggiunta banner: ${(e as Error).message}`,
		});
	}
};

export const updateBanner = async ({
	db,
	input,
}: {
	db: Querier;
	input: Banners;
}) => {
	try {
		return await db
			.updateTable("banners")
			.set({
				...input,
				idbanner: input.idbanner,
			})
			.where("banners.idbanner", "=", input.idbanner)
			.returning("banners.idbanner")
			.execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore aggiornamento banner: ${(e as Error).message}`,
		});
	}
};

export const deleteBanner = async ({
	db,
	input,
}: {
	db: Querier;
	input: { idbanner: BannersIdbanner };
}) => {
	try {
		await db
			.deleteFrom("banners")
			.where("banners.idbanner", "=", input.idbanner)
			.execute();
		return "ok";
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore eliminazione banner: ${(e as Error).message}`,
		});
	}
};
