<?php
/**
 * Resumable scan discovery.
 *
 * @package LocalGuardScanner
 */

namespace LocalGuardScanner\Application\Scan;

use LocalGuardScanner\Detection\Filesystem\FileEnumerator;

/**
 * Counts filesystem objects without hashing or reading their content.
 */
final class ScanDiscoveryService {
	/** @var FileEnumerator */
	private $enumerator;

	/** @param FileEnumerator $enumerator Resumable enumerator. */
	public function __construct( FileEnumerator $enumerator ) {
		$this->enumerator = $enumerator;
	}

	/**
	 * @param string              $root     WordPress root.
	 * @param array<string,mixed> $cursor   Discovery cursor.
	 * @param int                 $limit    Directory-entry budget.
	 * @param string[]            $excluded Excluded directories.
	 * @return array{cursor:array<string,mixed>,count:int,done:bool,omissions:array<string,int>,current_area:string}
	 */
	public function next_batch( $root, array $cursor, $limit, array $excluded = array() ) {
		$batch = $this->enumerator->next_batch( $root, $cursor, $limit, $excluded );
		$next  = $batch->cursor();
		$area  = isset( $next['current'] ) && is_string( $next['current'] ) ? $next['current'] : '';
		if ( '' === $area && isset( $next['queue'][0] ) && is_string( $next['queue'][0] ) ) {
			$area = $next['queue'][0];
		}
		return array(
			'cursor'       => $next,
			'count'        => count( $batch->items() ),
			'done'         => $batch->done(),
			'omissions'    => $batch->omissions(),
			'current_area' => $area,
		);
	}
}
