# frozen_string_literal: true

require 'benchmark/ips'

project = Project.find(1)

Benchmark.ips do |bench|
  bench.report('Redmine 5.1.0') do
    project.reload
    users =
      project.members.preload(:principal).select do |m|
        m.principal.present? &&
         (m.mail_notification? || m.principal.mail_notification == 'all')
      end
    users.collect {|m| m.principal}
  end

  # The last version before `preload(:principal)` was added in r15518
  bench.report('Redmine 3.2.6') do
    project.reload
    project.members.select {|m| m.principal.present? && (m.mail_notification? || m.principal.mail_notification == 'all')}.collect {|m| m.principal}
  end

#  bench.report('has_many_through') do
#    project.reload
#    project.users.where('members.mail_notification = ? OR users.mail_notification = ?', true, 'all').to_a
#  end

  bench.report('#23328#note-8') do
    project.reload
    subquery =
      project.members.select(:user_id)
      .where.associated(:principal)
      .where('members.mail_notification = ? OR users.mail_notification = ?', true, 'all')
    User.where(id: subquery).to_a
  end

  bench.report('#23328#note-2') do
    project.reload
    project.members.eager_load(:principal).find_each()
      .select {|m| m.principal.present? && (m.mail_notification? || m.principal.mail_notification == 'all')}
      .collect {|m| m.principal}
  end

  bench.compare!
end
