# Usage:
#
# Dry run: rake single_use:replace_community_monitor_phase_report
# Execute: rake single_use:replace_community_monitor_phase_report[execute]
namespace :single_use do
  desc 'Replace community monitor phase report'
  task :replace_community_monitor_phase_report, %i[execute] => [:environment] do |_t, args|
    execute = args[:execute] == 'execute'

    def print_padded(text)
      puts '=' * 20
      puts "\n\n"
      puts text
      puts "\n\n"
      puts '=' * 20
    end

    Tenant.safe_switch_each do |tenant|
      print_padded "\nProcessing tenant #{tenant.host} \n\n"

      app_config = AppConfiguration.instance

      # Step 1: get all community monitor reports
      community_monitor_project_id = app_config.settings.dig('community_monitor', 'project_id')

      if community_monitor_project_id.nil?
        print_padded 'Community monitor project id not specified'
        next
      end

      community_monitor_phase = Phase.find_by(project_id: community_monitor_project_id)

      if community_monitor_phase.nil?
        print_padded 'Community monitor phase not found'
        raise 'Community monitor phase not found'
      end

      community_monitor_reports = ReportBuilder::Report
        .where(phase_id: community_monitor_phase.id)

      if community_monitor_reports.empty?
        print_padded 'No community monitor autogenerated reports found'
        next
      end

      # Step 2: for each report, remove phase and set community_monitor to true
      community_monitor_reports.each do |report|
        if execute
          report.phase_id = nil
          report.community_monitor = true

          report.save!
        else
          print_padded "Would update report #{report.id}"
        end
      end
    end
  end
end
