module JamRuby
  class TestGearReminder

    @@log = Logging.logger[TestGearReminder]

    def self.send_reminders
      begin
        cutoff_date = Date.parse(Rails.application.config.test_gear_reminders_effective_from_date) # Define a cutoff date for the test gear setup emails
        reminder1_users(cutoff_date).find_each(batch_size:100) do |user|
          UserMailer.test_gear_reminder1(user).deliver_now
          User.where(id: user.id).update_all(test_gear_reminder1_sent_at: Time.now)
        end

        reminder2_users(cutoff_date).find_each(batch_size:100) do |user|
          UserMailer.test_gear_reminder2(user).deliver_now
          User.where(id: user.id).update_all(test_gear_reminder2_sent_at: Time.now)
        end

        reminder3_users(cutoff_date).find_each(batch_size:100) do |user|
          UserMailer.test_gear_reminder3(user).deliver_now
          User.where(id: user.id).update_all(test_gear_reminder3_sent_at: Time.now)
        end
      rescue Exception => e
        @@log.error("unable to send TestGearReminder email #{e}")
        puts "unable to send TestGearReminder email #{e}"
      end
    end

    def self.prospect_users
      User.where("users.first_music_session_at IS NULL")
    end

    def self.reminder1_users(cutoff_date)
      TestGearReminder.prospect_users.where("users.first_certified_gear_at < ? AND users.created_at >= ? AND users.test_gear_reminder1_sent_at IS NULL", 1.day.ago, cutoff_date)
    end

    def self.reminder2_users(cutoff_date)
      TestGearReminder.prospect_users.where("users.first_certified_gear_at < ? AND users.created_at >= ? AND users.test_gear_reminder1_sent_at IS NOT NULL AND users.test_gear_reminder2_sent_at IS NULL", 3.days.ago, cutoff_date)
    end

    def self.reminder3_users(cutoff_date)
      TestGearReminder.prospect_users.where("users.first_certified_gear_at < ? AND users.created_at > ? AND users.test_gear_reminder2_sent_at IS NOT NULL AND users.test_gear_reminder3_sent_at IS NULL", 5.days.ago, cutoff_date)
    end
  end
end