import { TRPCError } from "@trpc/server";
import { sql } from "kysely";
import { db } from "../db";

export const getComuni = async () => {
	try {
		return await db
			.selectFrom("comuni")
			.selectAll()
			.orderBy("nome", "asc")
			.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()
			.orderBy("nome", "asc")
			.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 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()
			.orderBy(sql`nome = 'ITALIA'`, "desc")
			.orderBy("nome", "asc")
			.execute();
	} catch (e) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Error while getting Nazioni: ${(e as Error).message}`,
		});
	}
};
