# List available plans
# Required environment: API_ORIGIN, SUBSCRIBER_ACCESS_TOKEN
# API_ORIGIN is the operator origin, without a /subscriber suffix.
# Optional QUERY_JSON: JSON object of query parameters, e.g. {"page":1,"limit":10}. Use only parameters listed for this endpoint.
# Makes one request; does not retry or follow redirects. After an uncertain write, check your order/SIM state before repeating.
# Save as plan_getAll.rb; run: ruby plan_getAll.rb (Ruby 2.6+, standard library).
require 'json'
require 'net/http'
require 'uri'

def required(name)
  value = ENV[name]
  raise 'Set ' + name if value.nil? || value.empty?
  value
end
origin = URI(required('API_ORIGIN'))
raise 'API_ORIGIN must be an HTTP(S) origin only' unless %w[http https].include?(origin.scheme) && origin.host && !origin.userinfo && ['', '/'].include?(origin.path) && !origin.query && !origin.fragment
url = URI(origin.to_s.sub(%r{/$}, '') + "/subscriber/plan")
query = JSON.parse(ENV.fetch('QUERY_JSON', '{}'))
url.query = URI.encode_www_form(query.map { |key, value| [key, value.is_a?(Array) ? value.join(',') : value.to_s] }) unless query.empty?
request = Net::HTTP::Get .new(url.request_uri)
request['Authorization'] = 'Bearer ' + required('SUBSCRIBER_ACCESS_TOKEN')
begin
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = url.scheme == 'https'
  http.open_timeout = 30
  http.read_timeout = 30
  http.max_retries = 0 if http.respond_to?(:max_retries=)
  response = http.request(request)
  puts 'HTTP ' + response.code
  text = response.body.to_s
  unless text.empty?
    begin
      puts JSON.pretty_generate(JSON.parse(text))
    rescue JSON::ParserError
      puts text
    end
  end
  exit(response.code.to_i.between?(200, 299) ? 0 : 1)
rescue StandardError => error
  warn 'Request failed: ' + error.message
  exit 1
end
