import { TRPCError } from "@trpc/server";
import type { ComuniId } from "~/schemas/public/Comuni";
import type { NazioniId } from "~/schemas/public/Nazioni";
import { db } from "../db";

export const getComuni = async () => {
	try {
		return await db.selectFrom("comuni").selectAll().execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Error while getting Comuni: ${(e as Error).message}`,
		});
	}
};

export const searchComuniByCatasto = async (catasto: string[]) => {
	try {
		return await db
			.selectFrom("comuni")
			.selectAll()
			.where("catasto", "in", catasto)
			.execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Error while getting Comuni: ${(e as Error).message}`,
		});
	}
};
export const getComuneById = async (id: ComuniId) => {
	try {
		return await db
			.selectFrom("comuni")
			.selectAll()
			.where("id", "=", id)
			.executeTakeFirst();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Error while getting ComuneById: ${(e as Error).message}`,
		});
	}
};

export const getProvincie = async () => {
	try {
		return await db.selectFrom("provincie").selectAll().execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Error while getting Provincie: ${(e as Error).message}`,
		});
	}
};

export const getNazioni = async () => {
	try {
		return await db.selectFrom("nazioni").selectAll().execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Error while getting Nazioni: ${(e as Error).message}`,
		});
	}
};
export const getNazioneById = async (id: NazioniId) => {
	try {
		return await db
			.selectFrom("nazioni")
			.selectAll()
			.where("id", "=", id)
			.executeTakeFirst();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Error while getting NazioneById: ${(e as Error).message}`,
		});
	}
};
