class AwsIamAccessKeys::Backend::AwsUserIterator

using the Credential Report.
TODO: An alternate, more scalable implementation could be made
all users, then fetching their access keys.
Implementation of AccessKeyProvider which operates by looping over

def add_synthetic_fields(key_info, user_details) # rubocop:disable Metrics/AbcSize

rubocop:disable Metrics/AbcSize
def add_synthetic_fields(key_info, user_details) # rubocop:disable Metrics/AbcSize
  key_info[:id] = key_info[:access_key_id]
  key_info[:active] = key_info[:status] == 'Active'
  key_info[:inactive] = key_info[:status] != 'Active'
  key_info[:created_hours_ago] = ((Time.now - key_info[:create_date]) / (60*60)).to_i
  key_info[:created_days_ago] = (key_info[:created_hours_ago] / 24).to_i
  key_info[:user_created_date] = user_details[:create_date]
  key_info[:created_with_user] = (key_info[:create_date] - key_info[:user_created_date]).abs < 1.0/24.0
  # Last used is a separate API call
  iam_client = aws_service_client
  last_used =
    iam_client.get_access_key_last_used(access_key_id: key_info[:access_key_id])
              .access_key_last_used.last_used_date
  key_info[:ever_used] = !last_used.nil?
  key_info[:never_used] = last_used.nil?
  key_info[:last_used_time] = last_used
  return unless last_used
  key_info[:last_used_hours_ago] = ((Time.now - last_used) / (60*60)).to_i
  key_info[:last_used_days_ago] = (key_info[:last_used_hours_ago]/24).to_i
end

def fetch(criteria)

def fetch(criteria)
  iam_client = aws_service_client
  user_details = {}
  if criteria.key?(:username)
    begin
      user_details[criteria[:username]] = iam_client.get_user(user_name: criteria[:username]).user
    rescue Aws::IAM::Errors::NoSuchEntity # rubocop:disable Lint/HandleExceptions
      # Swallow - a miss on search results should return an empty table
    end
  else
    pagination_opts = {}
    loop do
      api_result = iam_client.list_users(pagination_opts)
      api_result.users.each do |info|
        user_details[info.user_name] = info
      end
      break unless api_result.is_truncated
      pagination_opts[:marker] = api_result.marker
    end
  end
  access_key_data = []
  user_details.each_key do |username|
    begin
      user_keys = iam_client.list_access_keys(user_name: username)
                            .access_key_metadata
      user_keys = user_keys.map do |metadata|
        {
          access_key_id: metadata.access_key_id,
          username: username,
          status: metadata.status,
          create_date: metadata.create_date, # DateTime.parse(metadata.create_date),
        }
      end
      # Copy in from user data
      # Synthetics
      user_keys.each do |key_info|
        add_synthetic_fields(key_info, user_details[username])
      end
      access_key_data.concat(user_keys)
    rescue Aws::IAM::Errors::NoSuchEntity # rubocop:disable Lint/HandleExceptions
      # Swallow - a miss on search results should return an empty table
    end
  end
  access_key_data
end