require 'net/http'
require 'json'

# Kenna Security API Client
#   Requests are limited to a maximum of 5 requests per second.
#   If you exceed this limit, your request will receive a “429: Too Many Requests" status code response.

class APIClient
  attr_accessor :api_token, :api_url

  def initialize(api_token)
    @api_token = api_token
    @api_url = 'https://api.kennasecurity.com'
  end

  def vuln_id(id)
    get("/vulnerabilities/#{id}")
  end

  def asset_id(id)
    get("/assets/#{id}")
  end

  def headers(request)
    request['X-Risk-Token'] = api_token
    request['Content-type'] = 'application/json'
    request
  end

  def show_errors(response)
    response_errors = lambda do |error|
      {
        'response_code': error.code,
        'response_message': error.message,
        'response_class_name': error.class.name
      }
    end
    response_errors.call response
  end

  def handle_response(response)
    if response.is_a?(Net::HTTPSuccess)
      JSON.parse(response.body)
    else
      show_errors(response)
    end
  end

  def get(uri)
    # pass a relative url: example - /vulnerabilities
    url = URI("#{api_url}/#{uri}")
    request = Net::HTTP::Get.new(url)
    request = headers(request)

    response = Net::HTTP.start(url.hostname, url.port, use_ssl: true) do |http|
      http.request(request)
    end

    handle_response(response)
  end
end