"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dnsLookup = lookup;
exports.printDnsStats = printDnsStats;
exports.clearDnsCache = clearDnsCache;
const node_dns_1 = require("node:dns");
const lru_cache_1 = require("lru-cache");
const logger_1 = require("../../logger");
const cache = new lru_cache_1.LRUCache({ max: 1000 });
function lookup(...[host, options, callback]) {
    let opts;
    // TODO: strict null incompatible types (#22198)
    let cb;
    if (typeof options === 'function') {
        opts = {};
        cb = options;
    }
    else if (typeof options === 'number') {
        opts = { family: options };
        cb = callback;
    }
    else {
        opts = options;
        cb = callback;
    }
    // istanbul ignore if: not used
    if (opts.all) {
        const key = `${host}_all`;
        if (cache.has(key)) {
            logger_1.logger.trace({ host }, 'dns lookup cache hit');
            cb(null, cache.get(key));
            return;
        }
        (0, node_dns_1.lookup)(host, opts, (err, res) => {
            if (err) {
                logger_1.logger.debug({ host, err }, 'dns lookup error');
                cb(err, null, null);
                return;
            }
            logger_1.logger.trace({ host, opts, res }, 'dns lookup');
            cache.set(key, res);
            cb(null, res, null);
        });
    }
    else {
        if (cache.has(host)) {
            logger_1.logger.trace({ host }, 'dns lookup cache hit');
            cb(null, ...cache.get(host));
            return;
        }
        (0, node_dns_1.lookup)(host, opts, (err, ...res) => {
            if (err) {
                logger_1.logger.debug({ host, err }, 'dns lookup error');
                cb(err);
                return;
            }
            logger_1.logger.trace({ host, opts, res }, 'dns lookup');
            cache.set(host, res);
            cb(null, ...res);
        });
    }
}
function printDnsStats() {
    logger_1.logger.debug({ hosts: Array.from(cache.keys()) }, 'dns cache');
}
function clearDnsCache() {
    cache.clear();
}
//# sourceMappingURL=dns.js.map