<?php

namespace RadiusTheme\RadiusBooking\Commands;

use WP_CLI;
use WP_CLI_Command;
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
/**
 * Generates a full module: Model, Repository, Resource, Service, Controller.
 */
class MakeModuleCommand extends WP_CLI_Command {

	/**
	 * Handles the invocation of the command that creates a new module by generating its associated components.
	 *
	 * @param array $args Positional arguments passed to the command. The first argument should be the module name.
	 * @param array $assoc_args Associative arguments passed to the command.
	 *
	 * @return void
	 */
	public function __invoke( $args, $assoc_args ) {
		$name = $args[0] ?? null;

		if ( ! $name ) {
			WP_CLI::error( 'Module name is required. Example: wp radius artisan make:module Location' );
		}

		$commands = array(
			"make:model {$name}",
			"make:repository {$name}Repository",
			"make:resource {$name}Resource",
			"make:service {$name}Service",
			"make:controller {$name}Controller",
		);

		foreach ( $commands as $cmd ) {
			WP_CLI::log( "➡ Running: wp radius artisan {$cmd}" );
			$this->runSubcommand( $cmd );
		}

		WP_CLI::success( "✅ Module '{$name}' created successfully." );
	}

	/**
	 * Executes a subcommand within the WP CLI Radius Artisan context.
	 *
	 * @param string $command The specific command to be executed, appended to the WP CLI Radius Artisan scope.
	 *
	 * @return void
	 */
	private function runSubcommand( string $command ) {
		$fullCommand = "wp radius artisan {$command}";
		exec( $fullCommand, $output, $resultCode );

		foreach ( $output as $line ) {
			WP_CLI::log( "   $line" );
		}

		if ( $resultCode !== 0 ) {
			WP_CLI::warning( "⚠ Failed: {$fullCommand}" );
		}
	}
}
