<?php

namespace WPDRMS\ASP\Cli;

use WP_CLI;
use WPDRMS\ASP\Cache\ResultsCacheService;

class Cache {
	/**
	 * Controls the cache for Ajax Search Pro.
	 *
	 * ## OPTIONS
	 *
	 * <clear|purge|info>
	 * : Action to perform.
	 *
	 * ## EXAMPLES
	 *
	 * # Clear stale (expired) cache items
	 * wp asp cache clear
	 *
	 * # Purge all cache items
	 * wp asp cache purge
	 *
	 * # Get cache info
	 * wp asp cache info
	 *
	 * @subcommand cache
	 * @when init
	 */
	public function index( array $args ): void {
		if ( !isset($args[0]) ) {
			WP_CLI::error('No cache action provided');
			return;
		}

		switch ( $args[0] ) {
			case 'info':
				$this->info();
				break;
			case 'clear':
				$this->clear();
				break;
			case 'purge':
				$this->purge();
				break;
			default:
				WP_CLI::error('Invalid cache action provided');
		}
	}

	private function info(): void {
		$realtime_stats = ResultsCacheService::instance()->search_statistics_query->getRealTimeSearchStatistics();
		WP_CLI::line('Cache hits past 24H: ' . $realtime_stats['last_24_hours']['hits']);
		WP_CLI::line('Cache hits all time: ' . $realtime_stats['all_time']['hits']);
		WP_CLI::line('Cache misses past 24H: ' . $realtime_stats['last_24_hours']['misses']);
		WP_CLI::line('Cache misses all time: ' . $realtime_stats['all_time']['misses']);
		WP_CLI::line('Total items in cache: ' . ResultsCacheService::instance()->count());
	}

	private function clear(): void {
		WP_CLI::line('Cleared ' . ResultsCacheService::instance()->clear() . ' stale items from the search cache.');
	}

	private function purge(): void {
		WP_CLI::line('Purged all ' . ResultsCacheService::instance()->purge() . ' items from the search cache.');
	}
}
