# frozen_string_literal: true

require_relative 'base'
require_relative '../expectations'

module PluginConfig
  module Operations
    class Register < Base
      def initialize(params)
        super
        @description = params[:description] || ''
      end

      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'] ||= []

        existing = data['plugins'].find { |p| p['name'] == plugin }
        if existing
          return {
            status: 'already_registered',
            plugin: plugin,
            path: path,
            verified: true
          }
        end

        data['plugins'] << {
          'name' => plugin,
          'source' => "./#{plugin}",
          'description' => @description
        }

        data['plugins'].sort_by! { |p| p['name'] }

        write_json(path, data)

        verifier = FileVerifier.new(path)
        readback = read_json(path)
        found = readback && readback['plugins']&.any? { |p| p['name'] == plugin }

        {
          status: 'registered',
          plugin: plugin,
          path: path,
          verified: found == true
        }
      end
    end
  end
end
