# frozen_string_literal: true

require_relative 'base'
require_relative '../expectations'

module PluginConfig
  module Operations
    class Disable < 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)

        unless data && data['enabledPlugins']&.key?(plugin_key)
          return {
            status: 'not_found',
            plugin: plugin_key,
            path: settings_path,
            verified: true,
            remaining_plugins: data ? (data['enabledPlugins'] || {}).keys.sort : []
          }
        end

        data['enabledPlugins'].delete(plugin_key)
        data['enabledPlugins'] = data['enabledPlugins'].sort.to_h

        write_json(settings_path, data)

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

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