# frozen_string_literal: true

require_relative 'base'
require_relative '../expectations'

module PluginConfig
  module Operations
    class Unregister < Base
      def call
        path = marketplace_file

        # Validate marketplace schema if file exists
        if path && File.exist?(path)
          check_result = Expectations.check(path, %w[name plugins])
          raise SchemaError, check_result unless check_result[:ok]
        end

        data = read_json(path)

        unless data
          return {
            status: 'error',
            error: "Marketplace file not found or invalid: #{path}"
          }
        end

        data['plugins'] ||= []

        original_count = data['plugins'].length
        data['plugins'].reject! { |p| p['name'] == plugin }

        if data['plugins'].length == original_count
          return {
            status: 'not_found',
            plugin: plugin,
            path: path,
            verified: true
          }
        end

        write_json(path, data)

        readback = read_json(path)
        absent = readback && readback['plugins']&.none? { |p| p['name'] == plugin }

        {
          status: 'unregistered',
          plugin: plugin,
          path: path,
          verified: absent == true
        }
      end
    end
  end
end
