const net = require("net");

function isPortAvailable(host, port) {
  return new Promise((resolve) => {
    const server = net.createServer();
    server.once("error", () => resolve(false));
    server.once("listening", () => {
      server.close(() => resolve(true));
    });
    server.listen(port, host);
  });
}

async function findAvailablePort(host, startPort, maxAttempts = 20) {
  const base = parseInt(String(startPort), 10) || 5000;
  for (let i = 0; i < maxAttempts; i += 1) {
    const port = base + i;
    if (await isPortAvailable(host, port)) return port;
  }
  throw new Error(`NO_FREE_PORT_IN_RANGE_${base}_${base + maxAttempts - 1}`);
}

function validatePort(port) {
  const n = parseInt(String(port), 10);
  if (!Number.isFinite(n) || n < 1024 || n > 65535) {
    const err = new Error("INVALID_PORT");
    err.status = 400;
    throw err;
  }
  return n;
}

module.exports = {
  isPortAvailable,
  findAvailablePort,
  validatePort,
};
