<?php
/**
 * Execution lifecycle module boundary.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\Execution;

use ScheduledChanges\Snapshot\SnapshotCoordinator;

use ScheduledChanges\Field\FieldRegistry;
use ScheduledChanges\Lock\LockManager;
use ScheduledChanges\Lock\WpdbLockManager;
use ScheduledChanges\Provider\ProviderRegistry;
use ScheduledChanges\Repository\RunRepository;

/**
 * Builds execution, lock, and readback services selected by the active module graph.
 */
final class ExecutionModule {
	public const MODULE_ID = 'scheduled-changes-execution';

	/**
	 * Creates the execution engine services.
	 *
	 * @param ProviderOperationHandler[] $operation_handlers Provider operation handlers.
	 */
	public function createServices(
		ProviderRegistry $providers,
		FieldRegistry $fields,
		RunRepository $runs,
		SnapshotCoordinator $snapshots,
		?LockManager $locks = null,
		array $operation_handlers = array()
	): ExecutionServices {
		$locks ??= new WpdbLockManager();
		$applier = new ProviderOperationApplier(
			$providers,
			$fields,
			$operation_handlers,
			$runs
		);
		$engine  = new ExecutionEngine(
			$runs,
			$applier,
			$locks,
			new ExecutionGuard(
				$snapshots,
				new ConflictDetector( $providers, $fields )
			)
		);

		return new ExecutionServices(
			$locks,
			$snapshots,
			$operation_handlers,
			$engine
		);
	}
}
