const ping = require("ping");

async function pingDataCenter(ip) {
  return ping.promise
    .probe(ip)
    .then((result) => result.time)
    .catch((error) => null);
}

async function getPingResults(dataCenters, clientIp) {
  const pingResults = {};

  const promises = dataCenters.map(async ({ name, ip }) => {
    const rtt = await pingDataCenter(ip);
    pingResults[name] = {
      ip,
      rtt: rtt !== null ? rtt : "N/A",
    };
  });

  await Promise.all(promises);
  return pingResults;
}

module.exports = {
  getPingResults,
};
