// const dns = require('node:dns'); // commonjs
import dns from 'node:dns'; // esm module
import util from 'node:util';
import color from 'chalk';

const IP_V = 4; // we use IP protocol version 4
const URL = 'google.de';

const getIpBy = (url, ipVersion = 4) => {
  return new Promise((resolve, reject) => {
    // async process
    dns.lookup(url, ipVersion, (error, address) => {
      if (error) {
        reject(error);
      } else {
        resolve({ address: address, family: ipVersion });
      }
    });
  });
};

// Promises Unterobjekt von Node
const getPromisesIpBy = (url, ipVersion = 4) => {
  // async process
  return dns.promises.lookup(url, ipVersion);
};

// Promisify Helferfunktion
const getPromisifyIpBy = util.promisify(dns.lookup);

// Test Cases:
getIpBy(URL, IP_V)
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(color.red(err));
  });

getPromisesIpBy(URL)
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(color.red(err));
  });

getPromisifyIpBy(URL, IP_V)
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(color.red(err));
  });
