local maxminddb = require("maxminddb")
local db = maxminddb.open("/etc/haproxy/geo/GeoLite2-ASN.mmdb")

-- 1. Получаем номер ASN
core.register_fetches("geoip_asn", function(txn)
    local client_ip = tostring(txn.f:src())
    if not client_ip then return "NO_IP" end
    local res = db:lookup(client_ip)
    if res then
        local asn = res:get("autonomous_system_number")
        if asn then return tostring(asn) end
    end
    return "UNKNOWN"
end)

-- 2. Получаем имя провайдера (Organization)
core.register_fetches("geoip_asn_name", function(txn)
    local client_ip = tostring(txn.f:src())
    if not client_ip then return "NO_IP" end
    local res = db:lookup(client_ip)
    if res then
        local org = res:get("autonomous_system_organization")
        if org then return tostring(org) end
    end
    return "UNKNOWN"
end)
