import type { Client } from "@fattureincloud/fattureincloud-ts-sdk";
import { TRPCError } from "@trpc/server";
import type { UsersId } from "~/schemas/public/Users";
import { db } from "~/server/db";
import { clientsApi, companyId } from "~/server/FattureInCloud";

// export const getClientList = async () => {
// 	const clients = await clientsApi.listClients(
// 		companyId,
// 		undefined,
// 		"detailed",
// 		undefined,
// 		undefined,
// 		100,
// 	);
// 	return clients.data;
// };

// export const searchClient = async (cognome: string) => {
// 	const clients = await clientsApi.listClients(
// 		companyId,
// 		undefined,
// 		"detailed",
// 		undefined,
// 		undefined,
// 		100,
// 		`name contains '${cognome}'`,
// 	);
// 	return clients.data;
// };
export const getClientFromCF = async (cf: string) => {
	if (cf.length < 11) {
		return null;
	}
	const clients = await clientsApi.listClients(
		companyId,
		undefined,
		"detailed",
		undefined,
		undefined,
		100,
		`tax_code = '${cf}'`,
	);
	return clients.data;
};

export const exportUserToFIC = async (userId: UsersId) => {
	try {
		const user = await db
			.selectFrom("users")
			.innerJoin("users_anagrafica", "users_anagrafica.userid", "users.id")
			.select([
				"users.email",
				"users.nome",
				"users.cognome",
				"users.telefono",
				"users_anagrafica.codice_fiscale",
				"users_anagrafica.provincia_residenza",
				"users_anagrafica.comune_residenza",
				"users_anagrafica.cap_residenza",
				"users_anagrafica.via_residenza",
				"users_anagrafica.civico_residenza",
			])
			.leftJoin(
				"nazioni",
				"nazioni.catasto",
				"users_anagrafica.nazione_residenza",
			)
			.select("nazioni.iso as nazione_iso")
			.leftJoin("comuni", "comuni.catasto", "users_anagrafica.comune_residenza")
			.select("comuni.nome as comune_nome")
			.where("users.id", "=", userId)
			.executeTakeFirstOrThrow();
		if (!user.nazione_iso) {
			throw new Error("Nazione non compatibile con esportazione FIC");
		}

		if (
			!user.cap_residenza ||
			!user.comune_residenza ||
			!user.provincia_residenza ||
			!user.via_residenza ||
			!user.nazione_iso
		) {
			throw new Error("Utente mancante dati necessari per esportazione FIC");
		}

		const comune =
			user.nazione_iso === "IT"
				? user.comune_nome || user.comune_residenza
				: user.comune_residenza;
		const clientData: Client = {
			name: `${user.cognome.toUpperCase()} ${user.nome.toUpperCase()}`.trim(),
			type: "person",
			first_name: user.nome.toUpperCase(),
			last_name: user.cognome.toUpperCase(),
			tax_code: user.codice_fiscale,
			address_street: `${user.via_residenza.toUpperCase().replace(".", "")}${user.civico_residenza ? ` ${user.civico_residenza}` : ""}`,
			address_postal_code: user.cap_residenza,
			address_city: comune.toUpperCase(),
			address_province: user.provincia_residenza.toUpperCase(),
			country_iso: user.nazione_iso,
			email: user.email,
			phone: user.telefono || undefined,
			ei_code: "0000000",
		};

		const req = await clientsApi.createClient(companyId, { data: clientData });

		if (req.status !== 200) {
			throw new Error(`Failed to create client in FIC: ${req.statusText}`);
		}

		return req.data;
	} catch (error) {
		if (error instanceof Error && "response" in error) {
			// Log the actual FIC validation response
			// biome-ignore lint/suspicious/noExplicitAny: <ok>
			console.error("FIC API response data:", (error as any).response?.data);
		}
		console.error("Error exporting user to FIC:", error);
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Failed to export user to Fatture In Cloud: ${(error as Error).message}`,
		});
	}
};

// function normalizeString(str: string): string {
// 	return str
// 		.toUpperCase()
// 		.replace("E'", "E")
// 		.replace("A'", "A")
// 		.replace("U'", "U")
// 		.replace("I'", "I")
// 		.replace("O'", "O")
// 		.replace("È", "E")
// 		.replace("É", "E")
// 		.replace("À", "A")
// 		.replace("Ù", "U")
// 		.replace("Ì", "I")
// 		.replace("Ò", "O");
// }

// type FICNation = {
// 	name: string;
// 	settings_name: string;
// 	iso: string;
// 	fiscal_iso: string;
// 	uic: string;
// 	banned: boolean;
// };

// const KnownConflicts: Record<string, string> = {
// 	BAHRAIN: "Z204",
// 	"BOSNIA ED ERZEGOVINA": "Z153",
// 	CINA: "Z210",
// 	KAZAKISTAN: "Z255",
// 	KENIA: "Z322",
// 	MACEDONIA: "Z148",
// 	MOLDAVIA: "Z140",
// 	"PORTO RICO": "Z518",
// 	RUSSIA: "Z154",
// 	"STATI UNITI": "Z404",
// };

// export const nazioniSync = async () => {
// 	const raw = readFileSync("fic_nations.json", "utf-8");
// 	const data: FICNation[] = (JSON.parse(raw) as { data: FICNation[] }).data;
// 	console.log(`Parsed ${data.length} FIC nations`);
// 	// console.log(data);
// 	const dbData = await db.selectFrom("nazioni").selectAll().execute();
// 	const dbNazioniMap = new Map(
// 		dbData.map((nazione) => [normalizeString(nazione.nome), nazione]),
// 	);
// 	const toUpdate: { catasto: string; iso: string }[] = [];
// 	for (const nation of data) {
// 		const normalizedName = normalizeString(nation.name);
// 		const existing = dbNazioniMap.get(normalizedName);
// 		if (existing) {
// 			if (existing.iso !== nation.iso) {
// 				// await db
// 				// 	.updateTable("nazioni")
// 				// 	.set({ iso: nation.iso })
// 				// 	.where("id", "=", existing.id)
// 				// 	.execute();
// 				toUpdate.push({ catasto: existing.catasto, iso: nation.iso });
// 			}
// 		} else {
// 			const k = KnownConflicts[normalizedName];
// 			if (k) {
// 				toUpdate.push({ catasto: k, iso: nation.iso });
// 				continue;
// 			}

// 			console.warn(
// 				`Nation ${nation.name.toUpperCase()} not found in DB, consider adding it with ISO ${nation.iso}`,
// 			);
// 		}
// 	}
// 	console.log("Nazioni to update:", toUpdate);
// 	//write a txt file with the update statements
// 	const updateStatements = toUpdate
// 		.map((u) => `('${u.catasto}', '${u.iso}')`)
// 		.join(",\n");
// 	const sql = `UPDATE nazioni SET iso = data.iso FROM (VALUES\n${updateStatements}\n) AS data(catasto, iso) WHERE nazioni.catasto = data.catasto;`;

// 	writeFileSync("nazioni_update.sql", sql);
//};

// export const ficCapSync = async () => {
// 	try {
// 		const comuni = await infosApi.listCities();
// 		const nazioni = await infosApi.listDetailedCountries();
// 		if (comuni.status === 200) {
// 			const data = comuni.data.data;
// 			if (data) {
// 				await db.transaction().execute(async (trx) => {
// 					for (const comune of data) {
// 						if (comune.city && comune.postal_code && comune.province) {
// 							await trx
// 								.updateTable("comuni")
// 								.set({
// 									cap: comune.postal_code,
// 								})
// 								.where("nome", "=", comune.city.toUpperCase())
// 								.execute();
// 						}
// 					}
// 				});
// 			}
// 		}
// 		if (nazioni.status === 200) {
// 			const data = nazioni.data.data;
// 			if (data) {
// 				await db.transaction().execute(async (trx) => {
// 					for (const nazione of data) {
// 						if (nazione.name && nazione.iso) {
// 							await trx
// 								.updateTable("nazioni")
// 								.set({
// 									iso: nazione.iso,
// 								})
// 								.where("nazioni.nome", "=", nazione.name.toUpperCase())
// 								.execute();
// 						}
// 					}
// 				});
// 			}
// 		}
// 	} catch (error) {
// 		console.error("Error syncing FIC catasto:", error);
// 	}
// };
