require 'faraday'
require 'capgun/error/bad_request'
require 'capgun/error/forbidden'
require 'capgun/error/not_acceptable'
require 'capgun/error/not_found'
require 'capgun/error/unauthorized'

module Capgun
  module Response
    class RaiseClientError < Faraday::Response::Middleware

      def on_complete(env)
        case env[:status].to_i
        when 400
          raise Capgun::Error::BadRequest.new(error_body(env[:body]), env[:response_headers])
        when 401
          raise Capgun::Error::Unauthorized.new(error_body(env[:body]), env[:response_headers])
        when 403
          raise Capgun::Error::Forbidden.new(error_body(env[:body]), env[:response_headers])
        when 404
          raise Capgun::Error::NotFound.new(error_body(env[:body]), env[:response_headers])
        when 406
          raise Capgun::Error::NotAcceptable.new(error_body(env[:body]), env[:response_headers])
        end
      end

    private

      def error_body(body)
        if body.nil?
          ''
        elsif body['message']
          body['message']
        elsif body['error']
          body['error']
        elsif body['errors']
          first = Array(body['errors']).first
          if first.kind_of?(Hash)
            first['message'].chomp
          else
            first.chomp
          end
        end
      end

    end
  end
end
