# Usage:
#
# Dry run: rake single_use:add_layout_to_community_monitor_reports
# Execute: rake single_use:add_layout_to_community_monitor_reports[execute]
namespace :single_use do
  desc 'Add layout to community monitor reports'
  task :add_layout_to_community_monitor_reports, %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 autogenerate 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_autogenerated_reports = ReportBuilder::Report
        .where(
          phase_id: community_monitor_phase.id
        )
        .where.not(year: nil) # Only auto-generated reports have a year

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

      # Step 2: confirm that all these reports do not have a layout,
      # and add a layout
      community_monitor_autogenerated_reports.each do |report|
        if report.layout.present?
          raise "Report #{report.id} already has a layout"
        elsif execute
          report.layout = ContentBuilder::Layout.new(
            craftjs_json: {},
            enabled: true,
            code: 'report'
          )
          report.save!

          print_padded "Added layout to report #{report.id}"
        else
          print_padded "Would add layout to report #{report.id}"
        end
      end
    end
  end
end
