local lrucache = require("resty.lrucache.pureffi")

local M = {}

function M.new(config) 
    local self = {}

    self.config = config
    self.cache = lrucache.new(1000)

    return self
end

local function get_cache_key(address)
    return "dns:" .. address
end

local function init_if_not_dns(config)
    local dns = require("resty.dns.resolver")
    local resolver = dns.new({
        nameservers = config.nameservers,
        retrans = config.retrans,
        timeout = config.timeout,
    })
end

function M.resolve(self, address)
    if not ngx.dns then
        init_if_not_dns(self.config)
    end

    local cache_key = get_cache_key(address)
    local cached_ips = self.cache:get(cache_key)
    if cached_ips then
        return cached_ips
    end

    local ips, err = ngx.dns.resolve(address)
    if err then
        return nil, err
    end

    self.cache:set(cache_key, ips, 300)

    return ips
end


return M