import dns from "node:dns";
import net from "node:net";

type IP = {
	success: boolean;
	message: string;
};
export const checkHostnamePort = async (host: string): Promise<boolean> => {
	const [hostname, port] = host.split(":");

	// a just incase to make sure we have the host name and port
	if (!hostname || !port) {
		return false;
	}

	// Resolve the hostname to an IP address
	const ip = (await checkHostUp(hostname)) as IP;

	if (!ip.success) {
		return false;
	}
	const portNum = parseInt(port, 10);

	const hostUp = (await pingHost(hostname, portNum)) as IP;

	if (!hostUp.success) {
		return false;
	}

	return true;
};

const pingHost = (host: string, port: number) => {
	return new Promise((res) => {
		const s = new net.Socket();

		s.setTimeout(2000);

		s.connect(port, host);

		s.on("connect", () => {
			s.destroy();
			res({
				success: true,
				message: "Server up",
			});
		});

		s.on("timeout", () => {
			s.destroy();
			res({
				success: true,
				message: "Server Offline or unreachable, please check connection",
			});
		});

		s.on("error", (e) => {
			s.destroy();
			return res({
				success: false,
				message: "Encountered error while checking if host:port up",
				error: e,
			});
		});
	});
};
const checkHostUp = (host: string) => {
	return new Promise((res) => {
		dns.lookup(host, (err, address) => {
			if (err) {
				return res({
					success: false,
					message: "Error connecting to the server",
					error: err,
				});
			} else {
				res({ success: true, message: "Server Ip", data: address });
			}
		});
	});
};

//checkHostnamePort("usmcd1vms036:1433");
