
# Do not edit, this file was generated by github.com/apex/rpc.

require 'net/http'
require 'net/https'
require 'json'

module Todo
  class Client
    # Error is raised when an API call fails due to a 4xx or 5xx HTTP error.
    class Error < StandardError
      attr_reader :type
      attr_reader :message
      attr_reader :status

      def initialize(status, type = nil, message = nil)
        @status = status
        @type = type
        @message = message
      end

      def to_s
        if @type
          "#{@status} response: #{@type}: #{@message}"
        else
          "#{@status} response"
        end
      end
    end

    # Initialize the client with API endpoint URL and optional authentication token.
    def initialize(url, auth_token = nil)
      @url = url
      @auth_token = auth_token
    end

    # Adds an item to the list.
    #
    # @param [Hash] params the input for this method.
    # @param params [String] :item The item to add.
    def add_item(params)
      call "add_item", params
    end

    # Returns all items in the list.
    def get_items
      call "get_items"
    end

    # Removes an item from the to-do list.
    #
    # @param [Hash] params the input for this method.
    # @param params [Number] :id The id of the item to remove.
    def remove_item(params)
      call "remove_item", params
    end

    private
  
    # call an API method with optional input parameters.
    def call(method, params = nil)
      url = @url + "/" + method
      header = { "Content-Type" => "application/json" }
  
      if @auth_token
        header["Authorization"] = "Bearer #{@auth_token}"
      end
  
      res = Net::HTTP.post URI(url), params.to_json, header
      status = res.code.to_i
  
      if status >= 400
        begin
          body = JSON.parse(res.body)
        rescue
          raise Error.new(status)
        end
        raise Error.new(status, body["type"], body["message"])
      end
  
      res.body
    end
  end
end
