class Ipapi
  include HTTParty
  BASE_URL = "https://api.ipapi.is/"
  API_KEY = Rails.application.credentials.ipapi_key

  def lookup(ip)
  response = self.class.get("#{BASE_URL}", query: { q: ip, key: API_KEY })
  response.parsed_response
end

  def self.lookup(ip) = new.lookup(ip)

  def multi_lookup(ips)
    ips = Array(ips)
    ips.each_slice(100).flat_map { |slice| post_data({ips: slice}) }
  end

  def data(ip)
    if ip.is_a?(Array)
      post_data(ip)
    else
      response = self.class.get("#{BASE_URL}", query: { q: ip, key: API_KEY })
      response.parsed_response
    end
  rescue JSON::ParserError
    {}
  end

  def post_data(ips)
    response = self.class.post("#{BASE_URL}",
      query: { key: API_KEY },
      body: { ips: ips }.to_json,
      headers: { 'Content-Type' => 'application/json' }
    )

    results = response.parsed_response

    results["response"].map do |ip, data|
      IPAddr.new(ip)
      cidr = data.dig("asn", "route")

      NetworkRange.add_network(cidr).tap { |acl| acl&.update(ip_api_data: data) }
    rescue IPAddr::InvalidAddressError
      puts "Skipping #{ip}"
      next
    end
  end
end