<?php
namespace QuantumCache\Cli;

\defined( 'ABSPATH' ) || exit;

use QuantumCache\Support\Maintenance;

/**
 * Clear all QuantumCache entries for the current site.
 *
 * ## OPTIONS
 *
 * [--yes]
 * : Skip the confirmation prompt.
 *
 * ## EXAMPLES
 *
 *     wp quantumcache flush
 *     wp quantumcache flush --yes
 *
 * @when after_wp_load
 */
final class FlushCommand {

	/**
	 * @param string[]             $args       Positional arguments (unused).
	 * @param array<string,string> $assoc_args Named arguments.
	 */
	public function __invoke( array $args, array $assoc_args ): void {
		$yes = \WP_CLI\Utils\get_flag_value( $assoc_args, 'yes', false );

		if ( ! $yes ) {
			\WP_CLI::confirm( 'This will delete all QuantumCache entries for this site. Proceed?' );
		}

		$start  = microtime( true );
		$result = Maintenance::purge_all();
		$ms     = round( ( microtime( true ) - $start ) * 1000, 1 );

		$removed = (int) ( $result['removed'] ?? 0 );
		$backend = (string) ( $result['backend'] ?? 'unknown' );
		$note    = (string) ( $result['note'] ?? '' );

		\WP_CLI::success(
			sprintf(
				'Flushed %d %s from %s backend in %sms.%s',
				$removed,
				1 === $removed ? 'entry' : 'entries',
				$backend,
				$ms,
				$note ? ' ' . $note : ''
			)
		);
	}
}
