<?php
/**
 * Module-contributed launch templates command.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\WpCli;

use ScheduledChanges\Capabilities\CapabilityManager;
use ScheduledChanges\Templates\LaunchTemplateCatalog;

/** Lists and displays reusable launch blueprints. */
final class LaunchTemplatesCommand extends ModuleCommand {
	private LaunchTemplateCatalog $templates;

	/** Creates the command for the selected template catalog. */
	public function __construct( LaunchTemplateCatalog $templates ) {
		$this->templates = $templates;
	}

	/**
	 * Lists templates or displays one template by ID.
	 *
	 * ## OPTIONS
	 *
	 * <subcommand>
	 * : Use list or show.
	 *
	 * [<id>]
	 * : Template ID for show.
	 *
	 * [--format=<format>]
	 * : Output format. Supports table, json, and csv.
	 *
	 * @param string[]            $args Positional arguments.
	 * @param array<string,mixed> $assoc_args Command options.
	 */
	public function __invoke( array $args, array $assoc_args ): void {
		$this->requireCapability( CapabilityManager::VIEW_SCHEDULES );
		$subcommand = (string) ( $args[0] ?? '' );

		if ( 'list' === $subcommand ) {
			$rows = array_map(
				static function ( array $template ): array {
					$operations = is_array( $template['operations'] ?? null ) ? $template['operations'] : array();
					$providers  = array_values(
						array_unique(
							array_filter(
								array_map( static fn ( $operation ): string => is_array( $operation ) ? (string) ( $operation['provider_id'] ?? '' ) : '', $operations )
							)
						)
					);

					return array(
						'id'              => (string) $template['id'],
						'name'            => (string) $template['name'],
						'providers'       => implode( ',', $providers ),
						'operation_count' => count( $operations ),
					);
				},
				$this->templates->all()
			);

			$this->formatRows( $rows, array( 'id', 'name', 'providers', 'operation_count' ), $assoc_args );
			return;
		}

		if ( 'show' !== $subcommand ) {
			\WP_CLI::error( 'Unknown templates subcommand. Use list or show <id>.' );
		}

		$template = $this->templates->find( (string) ( $args[1] ?? '' ) );
		if ( null === $template ) {
			\WP_CLI::error( 'Template was not found.' );
		}

		$this->formatAssoc( $template, $assoc_args );
	}
}
