# frozen_string_literal: true

require_relative "base"

module Neetob
  class CLI
    module NeetoDeploy
      module ConfigVars
        class Upsert < Base
          attr_accessor :apps, :required_config_vars_json_file_path,
            :required_config_vars_with_project_keys_json_file_path, :sandbox

          def initialize(apps, required_config_vars_json_file_path,
required_config_vars_with_project_keys_json_file_path, sandbox = false)
            super()
            @apps = apps
            @required_config_vars_json_file_path = required_config_vars_json_file_path
            @required_config_vars_with_project_keys_json_file_path =
              required_config_vars_with_project_keys_json_file_path
            @sandbox = sandbox
          end

          def run
            check_the_given_arguments
            inform_about_current_working_mode(sandbox) if apps.nil?
            apps_to_be_updated = apps.nil? ?
            read_json_file(required_config_vars_with_project_keys_json_file_path) :
            find_all_matching_apps_or_repos(apps, :neetodeploy, sandbox)
            inform_about_default_config_vars_file

            apps_to_be_updated.each do |app|
              required_config = apps.nil? ?
                app[1]
                : read_json_file(required_config_vars_json_file_path || default_config_vars_upsert_file_path)
              app = app[0] if apps.nil?

              if apps.nil? && sandbox && app != "neeto-dummy"
                ui.error("The \"#{app}\" app is not available in sandbox mode.")
                next
              end

              upsert_config_variables(app, required_config)
            end
          end

          private

            def upsert_config_variables(app, vars)
              ui.info("\nWorking on #{app}")
              vars.each do |key, val|
                ui.info(`neetodeploy env set #{key}='#{val}' -a #{app}`)
              end
            end

            def check_the_given_arguments
              if (!apps.nil? && !required_config_vars_with_project_keys_json_file_path.nil?) ||
                  (apps.nil? && required_config_vars_with_project_keys_json_file_path.nil?)
                ui.error("Please provide either apps or path to the config file with project keys")
                exit
              end
            end

            def default_config_vars_upsert_file_path
              File.expand_path("../../../../../data/config-vars-upsert.json", __dir__)
            end

            def inform_about_default_config_vars_file
              if !apps.nil? &&
                required_config_vars_with_project_keys_json_file_path.nil? && required_config_vars_json_file_path.nil?

                ui.info("Upserting config vars from the \"neetob/data/config-vars-upsert.json\" file")
              end
            end
        end
      end
    end
  end
end