import { TRPCError } from "@trpc/server";
import type { TestiEStringheStingaId } from "~/schemas/public/TestiEStringhe";
import type { Querier } from "~/server/db";

export const getStringhe = async ({ db }: { db: Querier }) => {
	try {
		return await db.selectFrom("testi_e_stringhe").selectAll().execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore nel recupero delle stringhe: ${(e as Error).message}`,
		});
	}
};
export const getStringheFiltered = async ({
	db,
	contains,
}: {
	db: Querier;
	contains: string;
}) => {
	try {
		return await db
			.selectFrom("testi_e_stringhe")
			.where("stinga_id", "like", `%${contains}%` as TestiEStringheStingaId)
			.selectAll()
			.execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore nel recupero delle stringhe - contains: ${contains}: ${(e as Error).message}`,
		});
	}
};

export const getStringa = async ({
	db,
	stringaId,
}: {
	db: Querier;
	stringaId: TestiEStringheStingaId;
}) => {
	try {
		return await db
			.selectFrom("testi_e_stringhe")
			.selectAll()
			.where("stinga_id", "=", stringaId)
			.executeTakeFirst();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore recupero stringa - stringaId: ${stringaId}: ${(e as Error).message}`,
		});
	}
};

export const newStringa = async ({
	db,
	stringaId,
	stringaValue,
}: {
	db: Querier;
	stringaId: TestiEStringheStingaId;
	stringaValue: string | null;
}) => {
	try {
		return await db
			.insertInto("testi_e_stringhe")
			.values({ stinga_id: stringaId, stringa_value: stringaValue })
			.returning("stinga_id")
			.execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore aggiunta della stringa - stringaId: ${stringaId}: ${(e as Error).message}`,
		});
	}
};

export const updateStringhe = async ({
	db,
	stringaId,
	stringaValue,
}: {
	db: Querier;
	stringaId: TestiEStringheStingaId;
	stringaValue: string | null;
}) => {
	try {
		return await db
			.updateTable("testi_e_stringhe")
			.set({ stringa_value: stringaValue })
			.where("stinga_id", "=", stringaId)
			.returning("stinga_id")
			.execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore aggiornamento stringa - stringaId: ${stringaId}: ${(e as Error).message}`,
		});
	}
};

export const deleteStringa = async ({
	db,
	stringaId,
}: {
	db: Querier;
	stringaId: TestiEStringheStingaId;
}) => {
	try {
		await db
			.deleteFrom("testi_e_stringhe")
			.where("stinga_id", "=", stringaId)
			.execute();
		return true;
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Errore cancellazione stringa - stringaId: ${stringaId}: ${(e as Error).message}`,
		});
	}
};
