class Prime::Eth2Staking::FetchValidatorStatuses
  def initialize(validators)
    @validators = validators
  end

  def fetch
    return {} if @validators.empty?

    status_history = fetch_status_history
    group_by_validator_pubkey(status_history)
  end

  private

  def group_by_validator_pubkey(status_history)
    status_history.each_with_object({}) do |validator_data, memo|
      memo[pubkey(validator_data['account'])] = validator_data['statuses'].map do |status|
        { status: status['status'], changed_at: status['time'] }
      end
    end
  end

  def fetch_status_history
    client.status_history(
      network: chain.network.name,
      chain_id: chain.slug,
      accounts: @validators.map(&:address)
    )
  end

  def client
    @client ||= Prime::Eth2Staking::Beacon::ValidatorStatusClient.new(
      chain.validators_status_api_url,
      authorization: chain.validators_status_api_key,
      timeout: 5
    )
  end

  def chain
    @chain ||= @validators.first&.beacon_chain
  end

  def pubkey(address)
    address.gsub(/^0x/, '')
  end
end
