class TOSJob < BaseJob
  def perform
    users = options["users"]
    total = users.count
    failed_logins = []

    users.each.with_index(1) do |login, index|
      at(index, total, tos_ban? ? "Banning #{login}" : "Unbanning #{login}")
      success = linear_retry(proc { perform_user(login) }, tries: 60, rate: 5)
      failed_logins << login unless success
    end

    if failed_logins.present?
      error_message = tos_ban? ? "Failed to ban " : "Failed to unban "
      error_message << failed_logins.join(", ")
      set_status(error_message: error_message)
    end
  end

  private

  def tos_ban?
    return options['job_type'] == 'tos_ban'
  end

  def perform_user(login)
    user = Twitch::User.new(login: login)

    if tos_ban?
      user_id = user.fetch_id
      user_status = Ripley::BatchGetPayoutType.call([user_id.to_s])[user_id.to_s]

      ban_affiliates = Twitch::User.booleanize(options["ban_affiliates"])
      ban_partners = Twitch::User.booleanize(options["ban_partners"])

      return false if user_status.is_affiliate && !ban_affiliates
      return false if user_status.is_partner && !ban_partners
      user.tos_ban(options)
    else
      user.tos_unban(options)
    end
  end
end
