import { io, type Socket } from "socket.io-client";
import { useAppStore } from "../hooks/useAppStore";

let socket: Socket | null = null;

export function getSocket() {
	const { serverIp, serverPort } = useAppStore.getState();

	//const port = Number(serverPort) >= 50000 ? "3000" : serverPort;
	const url = `http://${serverIp}:${serverPort}`;

	if (!socket) {
		socket = io(url, {
			path: "/lst/api/socket.io",
			withCredentials: true,
			autoConnect: true,
			reconnection: true,
			reconnectionAttempts: 5,
			reconnectionDelay: 1000,
		});
	}

	return socket;
}

export function connectSocket() {
	const socket = getSocket();

	if (!socket.connected && socket.disconnected) {
		socket.connect();
	}

	return socket;
}
