class Paya::UserService < Paya::ApplicationService
  def initialize(school, method, options)
    @method = method
    @options = options
    super(school)
  end

  def call
    return unless @method == :create

    response = JSON.parse(RestClient.post(endpoint, { user: data }, headers))
    create_auth_role(response)
    response
  rescue RestClient::Exception => e
    JSON.parse(e.response.body)
  end

  private
    def endpoint
      "#{base_uri}/users"
    end

    def create_auth_role(user)
      auth_roles = production_environment? ? ['152'] : ['132', '159']
      auth_roles.each do |auth_role_id|
        RestClient.post(
          "#{base_uri}/authroleusers",
          { authroleuser: auth_data(user, auth_role_id) },
          headers
        )
      end
    end

    def production_environment?
      Rails.env.production? && !Rails.application.secrets.staging
    end

    def auth_data(user, auth_role_id)
      {
        user_id: user['user']['id'],
        auth_role_id: auth_role_id
      }
    end

    def data
      {
        primary_location_id: @options[:location_id],
        last_name: 'Sycamore',
        email: 'paya@sycamoreleaf.com',
        username: "ss_#{@school.id}",
        password: "Sycamore!#{@school.id}",
        user_api_key: @options[:api_key],
        user_hash_key: @options[:hash_key],
        user_type_id: '300'
      }
    end
end
