<?php
/**
 * Tracker config utilities.
 *
 * @package Ealab\Deployer
 */

namespace EaLab\WP_Deployer\vendor\Ealab\Deployer\Utility;

use EaLab\WP_Deployer\vendor\Dakwamine\Component\ComponentBasedObject;

/**
 * Tracker config utilities.
 */
class TrackerConfigUtils extends ComponentBasedObject {
	/**
	 * Gets the hash of the given tracker config.
	 *
	 * This is useful for sharing with the repository.
	 *
	 * @param array<string,array>|null $tracker_config The tracker config.
	 *
	 * @return string The hash of the tracker definition.
	 */
	public static function buildTrackerConfigHash( ?array $tracker_config = null ): string {
		if ( null === $tracker_config ) {
			return sha1( 'null' );
		}

		// Ensure a consistent order.
		ksort( $tracker_config );

		return sha1( json_encode( $tracker_config ) );
	}

	/**
	 * Finds the plugin that maintains the given tracker.
	 *
	 * For example, redirection_404 is maintained by redirection.
	 * If multiple plugins maintain the same tracker, the first found activated plugin is returned.
	 *
	 * @param string $tracker_id The tracker ID.
	 *
	 * @return string|null The plugin slug, or null if not found.
	 */
	public static function findTrackerPlugin( string $tracker_id ): ?string {
		$plugins = Plugin::getPluginsByTrackerId( $tracker_id, array( 'first_only' => true ) );

		return empty( $plugins ) ? null : reset( $plugins )['slug'];
	}

	/**
	 * Gets the hash for the given complete config.
	 *
	 * @param array<string,array<string,mixed>> $complete_tracker_config The complete tracker config.
	 *
	 * @return array<string,array<string,mixed>> The hashed complete tracker config.
	 */
	public static function hashCompleteTrackerConfig( array $complete_tracker_config ): array {
		foreach ( $complete_tracker_config as $tracker_id => $tracker_config ) {
			$complete_tracker_config[ $tracker_id ] = static::buildTrackerConfigHash( $tracker_config );
		}

		return $complete_tracker_config;
	}
}
