import { db } from "../db/db.controller.js";
import { printerLog } from "../db/schema/printerLogs.schema.js";
import { createLogger } from "../logger/logger.controller.js";
import { returnFunc } from "../utils/returnHelper.utils.js";
import { tryCatch } from "../utils/trycatch.utils.js";

export type PrinterData = {
	ip: string;
	name: string;
	condition: string;
	message: string;
	date?: string;
	printerSN: string;
};

const log = createLogger({ module: "tcp", submodule: "create_server" });

export const printerListen = async (tcpData: PrinterData) => {
	const ip = tcpData.ip?.replace("::ffff:", "");

	// post the new message
	const { data, error } = await tryCatch(
		db
			.insert(printerLog)
			.values({
				ip,
				name: tcpData.name,
				condition: tcpData.condition,
				message: tcpData.message,
				printerSN: tcpData.printerSN,
			})
			.returning(),
	);

	if (error) {
		return returnFunc({
			success: false,
			level: "error",
			module: "tcp",
			subModule: "post",
			message: "Failed to post tcp printer data.",
			data: [],
			notify: false,
		});
	}

	if (data) {
		log.info({}, `${tcpData.name} sent a message over`);
		// TODO: send message over to the controller to decide what to do next with it
	}
};
