require 'httparty'
require_relative 'mapper'
require_relative 'fetch'
require_relative "../version"

# Class responsible for making calls to retrieve user information from the Unified Profile API
module RailsIbm
  module Uprofile
    module Bluepages
      class Search < Mapper
        def initialize(query)
          @query = [query].flatten

          fetch = RailsIbm::Uprofile::Bluepages::Fetch.new(uri: RailsIbm::Uprofile::BLUEPAGES_V3_URI)
          @response = fetch.execute(query: @query)
        end

        def search_type
          raise StandardError.new description: "#search_type should be overriden by #{self.class}"
        end

        def results(parsed: true, remap: false)
          search_results(parsed: parsed, remap: remap)
        end

        private

        def search_results(parsed:, remap:)
          raise StandardError.new description: "#search_results should be overriden by #{self.class}"
        end

        def result_for(query_term, remap)
          parsed_users(remap).select { |parsed_user| parsed_user.values.include? query_term }.first
        end

        def response_valid?
          @response.code >= 200 && @response.code <= 399
        end

        def parsed_users(remap)
          return [] unless response_valid?

          parsed_results = JSON.parse @response.body, symbolize_names: true
          parsed_results = parse_multiple_profiles([parsed_results]) if multiple_search

          [parsed_results].flatten.map { |result| parse_user result, %i[content], remap: remap }
        rescue JSON::ParserError
          []
        end

        def multiple_search
          @query.is_a?(Array) && @query.size >= 2
        end

        def parse_multiple_profiles(data)
          data.flatten.map { |p| p[:profiles] }.flatten
        end
      end
    end
  end
end
