import { TRPCError } from "@trpc/server";
import type { BanlistId } from "~/schemas/public/Banlist";
import type BanType from "~/schemas/public/BanType";
import type { Querier } from "~/server/db";

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

export const addBan = async ({
	db,
	type,
	value,
}: {
	db: Querier;
	type: BanType;
	value: string;
}) => {
	try {
		return await db
			.insertInto("banlist")
			.values({
				type,
				value,
			})
			.onConflict((oc) => oc.columns(["type", "value"]).doNothing())
			.returning("id")
			.executeTakeFirst();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore nel ban: ${(e as Error).message}`,
		});
	}
};

export const updateBan = async ({
	db,
	id,
	type,
	value,
}: {
	db: Querier;
	id: BanlistId;
	type: BanType;
	value: string;
}) => {
	try {
		await db
			.updateTable("banlist")
			.set({
				type,
				value,
			})
			.where("id", "=", id)
			.executeTakeFirst();
		return true;
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore nel modificare il ban: ${(e as Error).message}`,
		});
	}
};

export const removeBan = async ({ db, id }: { db: Querier; id: BanlistId }) => {
	try {
		await db.deleteFrom("banlist").where("id", "=", id).executeTakeFirst();
		return true;
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore nel rimuovere il ban: ${(e as Error).message}`,
		});
	}
};

export const isBanned = async ({
	db,
	data,
}: {
	db: Querier;
	data: Partial<Record<BanType, string>>;
}) => {
	try {
		const bans = await getBanList({ db });
		for (const ban of bans) {
			if (data[ban.type] === ban.value) {
				return true;
			}
		}
		return false;
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore nel verificare il ban: ${(e as Error).message}`,
		});
	}
};
