<?php
/**
 * Serial Executor Class
 *
 * Executes search queries sequentially (one after another) via HTTP requests.
 * This ensures all WordPress hooks (including MaplePress search intercept) are triggered.
 *
 * @package MaplePress_SearchSpeedTest
 */

class MPSS_Serial_Executor {

	/**
	 * Execute queries serially (one at a time) using WP_Query directly.
	 *
	 * @param array $queries Array of search query strings.
	 * @return array Results array with timing and metadata.
	 */
	public function execute( $queries ) {
		$results = array();

		foreach ( $queries as $index => $query ) {
			// Start timing
			$start_time = microtime( true );

			// Execute WordPress search directly using WP_Query
			$search_query = new WP_Query(
				array(
					's'              => $query,
					'post_type'      => 'any',
					'post_status'    => 'publish',
					'posts_per_page' => 10,
				)
			);

			// End timing
			$end_time    = microtime( true );
			$duration_ms = ( $end_time - $start_time ) * 1000;

			$results[] = array(
				'query'        => $query,
				'duration_ms'  => round( $duration_ms, 2 ),
				'result_count' => $search_query->found_posts,
				'timestamp'    => $start_time,
				'success'      => true,
			);

			// Reset post data
			wp_reset_postdata();

			// Small delay to prevent overwhelming the database (10ms)
			usleep( 10000 );
		}

		return $results;
	}
}
