<?php
/**
 * Provider and field discovery module boundary.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\Provider;

use ScheduledChanges\Audit\OwnershipCollisionLogger;
use ScheduledChanges\Field\FieldRegistry;
use ScheduledChanges\Repository\AuditRepository;

/**
 * Builds and registers the provider/field discovery foundation module.
 */
final class ProviderDiscoveryModule {
	public const MODULE_ID = 'scheduled-changes-provider-discovery';

	/**
	 * Creates provider discovery services without assuming a specific target type.
	 *
	 * @param FieldProvider[]             $builtins Built-in providers supplied by target modules.
	 * @param ProviderDiscoveryCache|null $cache Discovery cache override.
	 */
	public function createServices( array $builtins = array(), ?ProviderDiscoveryCache $cache = null ): ProviderDiscoveryServices {
		$providers = new ProviderRegistry();
		$fields    = new FieldRegistry(
			$providers,
			$cache ?? new ProviderDiscoveryCache()
		);
		$manager   = new ProviderManager( $providers, $fields, $builtins );

		return new ProviderDiscoveryServices( $providers, $fields, $manager );
	}

	/**
	 * Registers WordPress hooks owned by provider discovery.
	 */
	public function registerHooks( ProviderDiscoveryServices $services, AuditRepository $audit ): void {
		$services->manager()->registerHooks();

		$collision_logger = new OwnershipCollisionLogger( $audit );
		add_action( 'scheduled_changes_field_ownership_collision', array( $collision_logger, 'log' ) );
	}
}
