# frozen_string_literal: true

require_relative 'abstract_handler'
require_relative '../../utils/command'
require_relative '../../utils/runtime_name_ht'

module Hypertube
  module Core
    module Handler
      class RetrieveArrayHandler < Hypertube::Core::Handler::AbstractHandler
        def initialize
          @required_parameters_count = 1
        end

        def process(command)
          validate(command, @required_parameters_count, self.class.name)

          response = command.payload[0]
          normalized = self.class.normalize_array_like(response)

          if normalized
            Hypertube::Utils::Command.new(Hypertube::Utils::RuntimeNameHt::RUBY, Hypertube::Utils::CommandType::ARRAY, normalized)
          else
            raise ArgumentError, 'Invalid argument type for Hypertube::Core::Handler::RetrieveArrayHandler. Expected an array.'
          end
        end

        # Converts Array, Set, and other array-like values to a plain Array payload.
        def self.normalize_array_like(response)
          case response
          when Array
            response
          else
            if defined?(Set) && response.is_a?(Set)
              response.to_a
            end
          end
        end
      end
    end
  end
end
