/**
 * the route that listens for the printers post.
 *
 * and http-post alert should be setup on each printer pointing to at min you will want to make the alert for
 * pause printer, you can have all on here as it will also monitor and do things on all messages
 *
 * http://{serverIP}:2222/lst/api/ocp/printer/listener/{printerName}
 *
 * the messages will be sent over to the db for logging as well as specific ones will do something
 *
 * pause will validate if can print
 * close head will repause the printer so it wont print a label
 * power up will just repause the printer so it wont print a label
 */

import { Router } from "express";
import multer from "multer";
import { db } from "../db/db.controller.js";
import { printerLog } from "../db/schema/printerLogs.schema.js";
import { apiReturn } from "../utils/returnHelper.utils.js";
import { tryCatch } from "../utils/trycatch.utils.js";

type PrinterEvent = {
	name: string;
	condition: string;
	message: string;
};
const r = Router();
const upload = multer();

const parseZebraAlert = (body: any): PrinterEvent => {
	const name = body.uniqueId || "unknown";
	const decoded = decodeURIComponent(body.alertMsg || "");

	const [conditionRaw, ...rest] = decoded.split(":");
	const condition = conditionRaw?.toLowerCase()?.trim() || "unknown";
	const message = rest.join(":").trim();

	return {
		name,
		condition,
		message,
	};
};

r.post("/:printer", upload.any(), async (req, res) => {
	const { printer: printerName } = req.params;
	const event: PrinterEvent = parseZebraAlert(req.body);

	const rawIp =
		req.headers["x-forwarded-for"]?.toString().split(",")[0]?.trim() ||
		req.socket.remoteAddress ||
		req.ip;

	const ip = rawIp?.replace("::ffff:", "");

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

	if (error) {
		return apiReturn(res, {
			success: false,
			level: "info",
			module: "ocp",
			subModule: "printing",
			message: `${printerName} encountered an error posting the log`,
			data: error as any,
			status: 400,
		});
	}

	if (data) {
		// TODO: send message over to the controller to decide what to do next with it
	}

	return apiReturn(res, {
		success: true,
		level: "info",
		module: "ocp",
		subModule: "printing",
		message: `${printerName} just sent a message`,
		data: req.body ?? [],
		status: 200,
	});
});

export default r;
