module Support
  module Services
    class OwsFeatures
      include HTTParty

      base_uri DOMAINS[:ows_features]

      class << self
        def active_variant_for_user(feature_name, user_id)
          path = "/features/user/#{user_id}"

          response = get(path)

          verify_success(response)
          JSON.parse(response.body)[feature_name]
        end

        def update_feature(feature_name, user_id, new_variant)
          path = "/features/#{feature_name}/user/#{user_id}"
          body = { "variant_name": new_variant }.to_json
          headers = { "Content-Type" => "application/json" }

          response = put(
            path,
            body: body,
            headers: headers
          )

          verify_success(response)
        end

        def get_user_features(user_id)
          path = "/features/user/#{user_id}"

          response = get(path)

          verify_success(response)
          JSON.parse(response.body)
        end

        private

        def verify_success(response)
          return if response.code == 200
          fail(
            "request to ows-features did not succeed:"\
            " #{JSON.parse(response.body)}"
          )
        end
      end
    end
  end
end
