namespace :information_requests do
  desc 'Set confirmed at to confirmed requests'
  task :load => :environment do
    InformationRequest.where(confirmed: true).all.each do |i|
      i.update_column(:confirmed_at, i.created_at) unless i.confirmed_at.present?
    end
  end
  desc 'Clear all test information requests'
  task :clear => :environment do
    # destroy all requests from admin
    InformationRequest.where(from_website: false).destroy_all
    # destroy all comments, events and customized fields from wensite requests
    existents = InformationRequest.where(from_website: true)
    Comment.where(commentable_type: 'InformationRequest', commentable_id: existents.map(&:id)).destroy_all
    InformationRequestEvent.where(eventable_type: 'InformationRequest', eventable_id: existents.map(&:id)).destroy_all
    existents.update_all(delivery_deadline: nil, extension_type: nil, information_type: nil, resolution_type: nil, redirected_institution_id: nil)
    # destroy all calendar events
    CalendarEvent.destroy_all
    # destroy all history records
    InformationRequestRecord.destroy_all
  end
  desc 'Set admitted_at = confirmed_at'
  task :admitted => :environment do
    InformationRequest.all.each{|i| i.update_column(:admitted_at, i.confirmed_at)}
  end
  desc 'Move older requirements to new requirements table'
  task :move_requirements => :environment do
    Comment.requirements.each do |comment|
      unless comment.information_request_requirements.size > 0
        if comment.closed?
          closed_state = comment.events.select{|e| e.state == 'closed'}.first
          if comment.information_type.present? and comment.resolution_type.present?
            r = comment.information_request_requirements.build
            r.information_type = comment.information_type
            r.resolution_type = comment.resolution_type
            r.created_at = closed_state.created_at
            r.updated_at = closed_state.updated_at
            r.weight = 1
            r.redirected_id = comment.commentable.redirected_institution_id
            r.save
          end
        end
      end
    end
  end
  namespace :reports do
    desc 'Send reports to OIR'
    task :oir => :environment do
      UserMailer.information_request_report_oir.deliver
    end
    desc 'Send reports to SSTA'
    task :ssta => :environment do
      if InformationRequest.confirmed.where(confirmed_at: 1.day.ago.beginning_of_day .. Date.current.beginning_of_day).count > 0
        UserMailer.information_request_report_ssta.deliver
      end
    end
    desc 'Send capres reports to SSTA'
    task :capres => :environment do
      if InformationRequest.confirmed.where(confirmed_at: 1.week.ago.beginning_of_day .. Date.current.beginning_of_day, institution_id: 9).count > 0
        UserMailer.information_request_report_capres_ssta.deliver
      end
    end
  end
end
