import { promisify } from 'util';
import { exec } from 'child_process';
import { Socket } from 'net';

// Status Check Bin Source Code is at:
// https://git.ssh.surf/hypermc/mc-status

const execPromise = promisify(exec);

export async function checkConnectionStatus(hostname, port) {
  try {
    const { stdout, stderr } = await execPromise(`${process.env.STATUS_CHECK_PATH} -host ${hostname} -port ${port}`);
    if (stderr) return { isOnline: false, error: stderr };
    return { isOnline: true, data: JSON.parse(stdout) };
  } catch (error) {
    return { isOnline: false, error: error.message };
  }
}

export async function checkGeyserStatus(hostname, port) {
  try {
    const { stdout, stderr } = await execPromise(`${process.env.GEYSER_STATUS_CHECK_PATH} -host ${hostname} -port ${port}`);
    if (stderr) return { isOnline: false, error: stderr };
    return { isOnline: true, data: JSON.parse(stdout) };
  } catch (error) {
    return { isOnline: false, error: error.message };
  }
}

export async function checkSftpStatus(hostname, port) {
  return new Promise((resolve) => {
    const socket = new Socket();
    const timeout = parseInt(process.env.SFTP_CONNECTION_TIMEOUT_MS, 10);
    socket.setTimeout(timeout);

    socket.on('connect', () => {
      socket.destroy();
      resolve({ isOnline: true });
    });

    socket.on('timeout', () => {
      socket.destroy();
      resolve({ isOnline: false, error: 'Connection timed out' });
    });

    socket.on('error', (error) => {
      socket.destroy();
      resolve({ isOnline: false, error: error.message });
    });

    socket.connect(port, process.env.SFTP_HOSTNAME);
  });
}