# frozen_string_literal: true

require_relative 'base'
require_relative '../expectations'

module PluginConfig
  module Operations
    class Enable < Base
      def call
        # Validate settings schema if file exists
        if File.exist?(settings_path)
          check_result = Expectations.check(settings_path, %w[enabledPlugins])
          raise SchemaError, check_result unless check_result[:ok]
        end

        data = read_json(settings_path) || { 'enabledPlugins' => {} }
        data['enabledPlugins'] ||= {}

        already = data['enabledPlugins'].key?(plugin_key)

        data['enabledPlugins'][plugin_key] = true
        data['enabledPlugins'] = data['enabledPlugins'].sort.to_h

        created = !File.exist?(settings_path)
        write_result = write_json(settings_path, data)

        verifier = FileVerifier.new(settings_path)
        key_check = verifier.verify_key('enabledPlugins', plugin_key, true)

        status = if already
                   'already_enabled'
                 elsif created
                   'created_and_enabled'
                 else
                   'enabled'
                 end

        {
          status: status,
          plugin: plugin_key,
          path: settings_path,
          verified: key_check[:verified],
          enabled_plugins: data['enabledPlugins'].keys.sort
        }
      end
    end
  end
end
