module JamRuby
  class GroupSessionReminder

    @@log = Logging.logger[GroupSessionReminder]

    def self.send_reminders
      begin
        cutoff_date = Date.parse(Rails.application.config.group_session_reminders_effective_from_date) # Define a cutoff date for the group session reminder emails

        reminder1_users(cutoff_date).find_each(batch_size:100) do |user|
          UserMailer.group_session_reminder1(user).deliver_now
          User.where(id: user.id).update_all(group_session_reminder1_sent_at: Time.now)
        end

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

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

    def self.prospect_users
      User.where("users.first_certified_gear_at IS NOT NULL AND users.first_real_music_session_at IS NULL")
    end

    def self.reminder1_users(cutoff_date)
      GroupSessionReminder.prospect_users.where("users.created_at > ? AND users.first_music_session_at IS NOT NULL AND users.group_session_reminder1_sent_at IS NULL", cutoff_date)
    end

    def self.reminder2_users(cutoff_date)
      GroupSessionReminder.prospect_users.where("users.created_at > ? AND users.group_session_reminder1_sent_at IS NOT NULL AND users.group_session_reminder2_sent_at IS NULL AND users.first_music_session_at < ?", cutoff_date, 3.days.ago)
    end

    def self.reminder3_users(cutoff_date)
      GroupSessionReminder.prospect_users.where("users.created_at > ? AND users.group_session_reminder2_sent_at IS NOT NULL AND users.group_session_reminder3_sent_at IS NULL AND users.first_music_session_at < ?", cutoff_date, 5.days.ago)
    end
    
  end
end