# frozen_string_literal: true

module Neetob
  class CLI
    module MonthlyAudit
      module InstancesAndAddons
        module NeetoDeploy
          class AutoScalingEnabled < CLI::Base
            def initialize
              super()
            end

            def run
              ui.success "### 3.1.4. Checking whether auto-scaling is enabled"

              apps_data = [["App", "Autoscaling config", "Comments", "Audit Passed"]]
              ui.info("\n", print_to_audit_log: false)
              Neetob::CLI::Sre::Base::APPS_LIST[:neetodeploy].select { |app| app.include?("production") }.each do |app|
                ui.info("Checking auto_scaling config for #{app}", print_to_audit_log: false)
                autoscaling_config_result = Neetob::CLI::NeetoDeploy::AutoscalingConfig.new(app).run
                audit_passed = nil
                comments = nil
                autoscaling_config = nil
                if autoscaling_config_result.is_a?(Hash) && autoscaling_config_result["error"] == "Forbidden"
                  audit_passed = "No"
                  comments = "You do not have permission to access the config for this app."
                else
                  autoscaling_config = JSON.parse(autoscaling_config_result.gsub("=>", ":"))
                  autoscaling_turned_on_for_web = autoscaling_config["web"]
                  autoscaling_turned_on_for_worker = autoscaling_config["worker"]

                  audit_passed = autoscaling_turned_on_for_web && autoscaling_turned_on_for_worker ? "Yes" : "No"
                  if audit_passed == "No"
                    comments = "Auto-scaling is not enabled for web and/or worker dynos."
                  end
                end
                apps_data << [app, autoscaling_config, comments, audit_passed]
              end
              ui.print_table(apps_data)
            end
          end
        end
      end
    end
  end
end