import { sql } from "drizzle-orm";
import { db } from "../../../pkg/db/db.js";
import { printers } from "../../../pkg/db/schema/printers.js";
import { createLogger } from "../../../pkg/logger/logger.js";
import { prodEndpoint } from "../../../pkg/utils/prodEndpoint.js";
import { tryCatch } from "../../../pkg/utils/tryCatch.js";

export const updatePrinters = async () => {
	const log = createLogger({
		module: "ocp",
		subModule: "update Printers",
	});
	const currentTime = new Date(Date.now());

	const { data: prodPrinters, error: prodError } = (await tryCatch(
		prodEndpoint("GET", "/public/v1.0/Administration/Printers"),
	)) as any;

	if (!prodPrinters.success) {
		log.error({ error: prodPrinters }, "There was an error with the endpoint");
		return;
	}

	if (prodError || prodPrinters?.data.length > 10000) {
		//console.log(prodError);
		return {
			success: false,
			message: "there was an error getting the printers.",
			data: prodError,
		};
	}

	// do the printer update into our db
	const prodPrinterInfo = prodPrinters?.data;

	for (let i = 0; i < prodPrinterInfo.length; i++) {
		const printerStuff: any = {
			humanReadableId: prodPrinterInfo[i].humanReadableId,
			name: prodPrinterInfo[i].name,
			ipAddress: prodPrinterInfo[i].ipAddress,
			port: prodPrinterInfo[i].port,
			remark: prodPrinterInfo[i].remark,
			processes: prodPrinterInfo[i].processes,
		};
		const { data, error } = await tryCatch(
			db
				.insert(printers)
				.values(printerStuff)
				.onConflictDoUpdate({
					target: printers.humanReadableId,
					set: {
						//humanReadableId: prodPrinterInfo[i].humanReadableId,
						name: prodPrinterInfo[i].name,
						ipAddress: prodPrinterInfo[i].ipAddress,
						port: prodPrinterInfo[i].port,
						remark: prodPrinterInfo[i].remark,
						processes: prodPrinterInfo[i].processes,
						upd_date: sql`NOW()`,
						//printDelay: "90", // need to remove in a couple weeks
					},
				}),
		);

		if (error) {
			log.error(
				{ error: error },
				`${
					prodPrinterInfo[i].name
				} encoutered and error adding/updating ${JSON.stringify(error)}`,
			);
		}
		log.debug({}, `${prodPrinterInfo[i].name} were just added/updated.`);
	}

	//await assignedPrinters();

	return { success: true, message: "Printers were just added or updated." };
};
