<?php
/**
 * Base class for module-specific WP-CLI sub-commands.
 *
 * @package BlaminhorEssentials
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
	return;
}

/**
 * Abstract parent for every `wp blaminhor <module>` sub-command class.
 *
 * Provides shared plumbing: capability enforcement, module lookup, and the
 * helper trait. Concrete commands set `$module_id` and implement their own
 * methods (get/set/test/etc.), delegating business logic to the underlying
 * module instance — never reimplementing validation.
 */
abstract class Blaminhor_Essentials_CLI_Module {

	use Blaminhor_Essentials_CLI_Helpers;

	/**
	 * Module ID this command operates on (matches the slug in `register_modules()`).
	 *
	 * @var string
	 */
	protected $module_id = '';

	/**
	 * Abort if the target module is not currently active.
	 */
	protected function ensure_module_active() {
		if ( '' === $this->module_id ) {
			WP_CLI::error( __( 'CLI command misconfigured: module_id is empty.', 'blaminhor-essentials' ) );
		}
		if ( ! $this->plugin()->is_module_active( $this->module_id ) ) {
			WP_CLI::error( sprintf(
				/* translators: 1: module ID, 2: module ID (repeated for the activation hint). */
				__( 'Module "%1$s" is not active. Run `wp blaminhor modules activate %2$s` first.', 'blaminhor-essentials' ),
				$this->module_id,
				$this->module_id
			) );
		}
	}

	/**
	 * Return the live module instance, aborting if unavailable.
	 *
	 * @return Blaminhor_Essentials_Module
	 */
	protected function get_module_instance() {
		$this->ensure_module_active();
		$modules = $this->plugin()->get_active_modules();
		if ( ! isset( $modules[ $this->module_id ] ) ) {
			WP_CLI::error( sprintf(
				/* translators: %s: module ID */
				__( 'Module "%s" could not be instantiated.', 'blaminhor-essentials' ),
				$this->module_id
			) );
		}
		return $modules[ $this->module_id ];
	}
}
