# lib/jam_ruby/lib/trial_expires_reminder.rb
#
# Sends reminder emails after a user's free trial has ended.
#
# Usage: JamRuby::TrialExpiresReminder.send_reminders
#
module JamRuby
  class TrialExpiresReminder
    @@log = Logging.logger[TrialExpiresReminder]

    FIRST_NOTIFICATION_CHECK = 1.day.ago.to_s
    SECOND_NOTIFICATION_CHECK = 5.days.ago.to_s
    THIRD_NOTIFICATION_CHECK = 9.days.ago

    def self.prospect_users(cutoff_date)
      User.where("(users.subscription_trial_ends_at IS NOT NULL AND users.subscription_trial_ends_at > ?)", cutoff_date)
    end

    def self.reminder1_users(cutoff_date)
      prospect_users(cutoff_date).where("users.subscription_last_checked_at < ? AND users.subscription_trial_ends_at < ? AND users.trial_expires_reminder1_sent_at IS NULL", 1.day.ago, FIRST_NOTIFICATION_CHECK)
    end

    def self.reminder2_users(cutoff_date)
      prospect_users(cutoff_date).where("users.subscription_last_checked_at < ? AND users.subscription_trial_ends_at < ? AND trial_expires_reminder1_sent_at IS NOT NULL AND users.trial_expires_reminder2_sent_at IS NULL", 1.day.ago, SECOND_NOTIFICATION_CHECK)
    end

    def self.reminder3_users(cutoff_date)
      prospect_users(cutoff_date).where("users.subscription_last_checked_at < ? AND users.subscription_trial_ends_at < ? AND trial_expires_reminder2_sent_at IS NOT NULL AND users.trial_expires_reminder3_sent_at IS NULL", 1.day.ago, THIRD_NOTIFICATION_CHECK)
    end

    def self.send_reminders
        cod = Date.parse(Rails.application.config.trial_expires_reminders_effective_from_date) # Define a cutoff date for the trial expires reminder emails

        reminder1_users(cod).find_each(batch_size: 100) do |user|
          begin
            UserMailer.trial_expires_reminder1(user).deliver_now
            user.update_attribute(:trial_expires_reminder1_sent_at, Time.now)
          rescue Exception => e
            @@log.error("unable to send trial_expires_reminder1 email #{e}")
            puts "unable to send trial_expires_reminder1 email #{e}"
          end
        end
        reminder2_users(cod).find_each(batch_size: 100) do |user|
          begin
            UserMailer.trial_expires_reminder2(user).deliver_now
            user.update_attribute(:trial_expires_reminder2_sent_at, Time.now)
          rescue Exception => e
            @@log.error("unable to send trial_expires_reminder2 email #{e}")
            puts "unable to send trial_expires_reminder2 email #{e}"
          end
        end
        reminder3_users(cod).find_each(batch_size: 100) do |user|
          begin
            UserMailer.trial_expires_reminder3(user).deliver_now
            user.update_attribute(:trial_expires_reminder3_sent_at, Time.now)
          rescue Exception => e
            @@log.error("unable to send trial_expires_reminder3 email #{e}")
            puts "unable to send trial_expires_reminder3 email #{e}"
          end
        end
    end
    
  end
end