require 'rake'

namespace :mail_rotator do

desc "creates rows MailRotator::MailerStore"
task update_rows: :environment do
  MailRotator::Switcher.validate_constant
  puts "MailRotator: Creating/updating mailer rows; please wait..."
  count = 0

  ActiveRecord::Base.transaction do
    MailRotator::Switcher::SMTP_SETTINGS.each do |name, options|
      mailer = MailRotator::MailerStore.where(name: name).first_or_initialize(sent_count: 0)
      mailer.limit = options[:limit] || options['limit']
      count += 1 if mailer.save!
    end
  end

  # destroy rows no longer valid:
  MailRotator::MailerStore.where("name NOT IN (?)", MailRotator::Switcher::SMTP_SETTINGS.keys).destroy_all

  # set an active mailer:
  MailRotator::MailerStore.where("").limit(1).update_all(active: true) unless MailRotator::MailerStore.where(active: true).exists?

  puts "MailRotator: Successfully created/updated #{count} mailer rows."
end

end