import { io, type Socket } from "socket.io-client";
import { createLogger } from "../logger/logger.controller.js";
import { systemSettings } from "../server.js";
import { getToken, odToken } from "./opendock.utils.js";

const log = createLogger({ module: "opendock", subModule: "releaseMonitor" });
const TWENTY_FOUR_HOURS = 24 * 60 * 60 * 1000;
let socket: Socket | null = null;
export const opendockSocketMonitor = async () => {
	// checking if we actaully want to run this
	if (!systemSettings.filter((n) => n.name === "opendock_sync")[0]?.active) {
		log.info({}, "Opendock is not active");
	}

	if (!odToken.odToken) {
		log.info({}, "Getting Auth Token");
		await getToken();
	}

	if (
		new Date(odToken.tokenDate || Date.now()).getTime() <
		Date.now() - TWENTY_FOUR_HOURS
	) {
		log.info({}, "Refreshing Auth Token");
		await getToken();
	}
	const baseSubspaceUrl = "wss://subspace.staging.opendock.com";
	const url = `${baseSubspaceUrl}?token=${odToken.odToken}`;
	socket = io(url, { transports: ["websocket"] }); // Enforce 'websocket' transport only.

	socket.on("connect", () => {
		console.log("Connected");
	});

	// socket.on("heartbeat", (data) => {
	// 	console.log(data);
	// });

	socket.on("create-Appointment", () => {
		//console.log("appt create:", data);
	});

	socket.on("update-Appointment", () => {
		//console.log("appt update:", data);
	});

	socket.on("error", (data) => {
		console.log("Error:", data);
	});

	// socket.onAny((event, ...args) => {
	// 	console.log("Received event:", event, args);
	// });
};

export const killOpendockSocket = () => {
	if (!socket) {
		console.log("No active socket to kill");
		return;
	}

	console.log("🛑 Killing socket connection...");

	socket.removeAllListeners(); // optional but clean
	socket.disconnect();
	socket = null;

	console.log("✅ Socket killed");
};
