import { formatDate } from "date-fns";
import type { Server, Socket } from "socket.io";
import { db } from "../../pkg/db/db.js";
import { orderScheduler } from "../../pkg/db/schema/orderScheduler.js";
import { tryCatch } from "../../pkg/utils/tryCatch.js";

let ioInstance: Server | null = null;

export const setupScheduler = (io: Server, socket: Socket) => {
	ioInstance = io;

	socket.on("joinScheduler", async () => {
		socket.join("scheduler");
		//console.log(`Socket ${socket.id} joined room "scheduler"`);

		const { data, error } = await tryCatch(db.select().from(orderScheduler));

		if (error) {
			setTimeout(() => {
				io.to("scheduler").emit("scheduler:update", {
					type: "init",
					error: error,
				});
			}, 1000);
			return;
		}

		// initial push
		setTimeout(() => {
			io.to("scheduler").emit("scheduler:update", { type: "init", data: data });
		}, 1000);
	});

	// socket.on("ping", () => {
	// 	io.to("scheduler").emit("pong", { from: socket.id });
	// });

	// setInterval(() => {
	// 	io.to("scheduler").emit("heartbeat", {
	// 		ts: formatDate(Date.now(), "M/d/yyyy HH:mm"),
	// 	});
	// }, 60_000);

	// add in listen for changes to the db with pg listen?
};

// --- Change Broadcast Function ---
export const schedulerChange = async (data: any) => {
	if (!ioInstance) {
		console.error("⚠️ schedulerChange called before setupScheduler initialized");
		return;
	}

	ioInstance.to("scheduler").emit("scheduler:update", {
		ts: formatDate(Date.now(), "M/d/yyyy HH:mm"),
		data,
	});
	console.log("📢 Scheduler update broadcasted:", data);
};
