# frozen_string_literal: true

namespace :kracken do
  namespace :sweep do
    desc "Remove expired credentials after threshold days " \
         "(default threshold is 90 days)"
    task :credentials, %i[threshold] => :environment do |_t, args|
      threshold = args.fetch(:threshold) { 90 }.to_i.days
      timestamp = threshold.ago
      Rails.logger.info "Clearing expired `Credentials` older than " \
                        "#{threshold.inspect} (#{timestamp})"
      expired = Credentials.where(expires: true)
                           .where("expires_at < ?", timestamp)
                           .destroy_all
                           .size
      Rails.logger.info "Removed: #{expired} credentials"
      threshold *= 2
      timestamp = threshold.ago
      Rails.logger.info "Clearing legacy `Credentials` older than " \
                        "#{threshold.inspect} (#{timestamp})"
      legacy = Credentials.where(expires: [nil, false])
                          .where("updated_at < ?", timestamp)
                          .destroy_all
                          .size
      Rails.logger.info "Removed: #{legacy} credentials"
    end
  end
end

# frozen_string_literal: true

namespace :kracken do
  namespace :sweep do
    desc "Remove expired credentials after threshold days " \
         "(default threshold is 90 days)"
    task :credentials, %i[threshold] => :environment do |_t, args|
      threshold = args.fetch(:threshold) { 90 }.to_i
      timestamp = threshold.days.ago
      Rails.logger.info "Clearing expired `Credentials` older than " \
                        "#{threshold.days.inspect} (#{timestamp})"
      expired = Credentials.where(expires: true)
                           .where("expires_at < ?", timestamp)
                           .destroy_all
                           .size
      Rails.logger.info "Removed: #{expired} credentials"
      threshold *= 2
      timestamp = threshold.days.ago
      Rails.logger.info "Clearing legacy `Credentials` older than " \
                        "#{threshold.days.inspect} (#{timestamp})"
      legacy = Credentials.where(expires: [nil, false])
                          .where("updated_at < ?", timestamp)
                          .destroy_all
                          .size
      Rails.logger.info "Removed: #{legacy} credentials"
    end
  end
end

Fix rake task for Rails 4.2
Fix rake task for Rails 4.2

Rails 4.2 does not preserve the duration type on multiplication:

  ```ruby
  x = 5.days
  # => 5 days

  x *= 2
  # => 864000
  ```

This fixes the Rake task so that we use the correct when calculating the
timestamp. In order to get the nicely worded output for the duration in
the logs we need to re-cast the duration at that point.
