import { Client } from "pg";
import { db } from "../db/db.js";
import { prodlabels } from "../db/schema/prodLabels.js";
import { tryCatch } from "../utils/tryCatch.js";
import { createLogger } from "./logger.js";

type NewLog = {
	level: string;
	username: string;
	service: string;
	message: string;
	checked: boolean;
	add_Date: Date;
};
export const v1Listener = async () => {
	const log = createLogger({ module: "logger", subModule: "Old logging app" });
	const client = new Client({
		connectionString: process.env.DATABASE_URL_V1,
	});

	await client.connect();

	// the notify channel to listen for logs on
	const channels = ["logs_channel", "label_channel", "orders_channel"];

	for (const ch of channels) {
		await client.query(`LISTEN ${ch}`);
	}

	log.info({ channels: channels }, "Listening for on channels");

	// create the log function to be able to mimic what is coming over
	const logEvent = (newLog: string) => {
		const newLogEvent: NewLog = JSON.parse(newLog);

		switch (newLogEvent.level) {
			case "info":
				log.info(
					{ username: newLogEvent.username, service: newLogEvent.service },
					newLogEvent.message,
				);
				break;
			case "error":
				log.error(
					{ username: newLogEvent.username, service: newLogEvent.service },
					newLogEvent.message,
				);
				break;
			default:
				log.info(
					{ username: newLogEvent.username, service: newLogEvent.service },
					newLogEvent.message,
				);
		}
	};

	const labelEvent = async (newLabel: string) => {
		const newLabelEvent: any = JSON.parse(newLabel);
		const { data, error } = await tryCatch(
			db.insert(prodlabels).values({
				printerID: newLabelEvent.printerID,
				printerName: newLabelEvent.printerName,
				line: newLabelEvent.line,
				runningNr: newLabelEvent.runningNr,
				status: newLabelEvent.status,
				add_user: newLabelEvent.add_user,
			}),
		);
	};
	client.on("notification", (msg) => {
		// msg.channel tells which channel it came from
		// msg.payload is whatever message you sent from the trigger
		switch (msg.channel) {
			case "logs_channel":
				logEvent(msg.payload || "");
				break;
			case "label_channel":
				labelEvent(msg.payload || "");
				break;
			case "orders_channel":
				console.log("🛒 Order event:", msg.payload);
				break;
			default:
				console.log("Other event:", msg);
		}
	});
};
