<?php
/**
 * Trigger Registry Class
 *
 * Central registry for all workflow triggers.
 *
 * @package Sequensy
 * @since 2.0.0
 */

declare(strict_types=1);

namespace Sequensy\Triggers;

use Sequensy\Registry\AbstractRegistry;
use Sequensy\Triggers\Contracts\TriggerHandler;

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Class TriggerRegistry
 *
 * Singleton registry for managing trigger handlers.
 * Extends AbstractRegistry for common registry functionality.
 */
class TriggerRegistry extends AbstractRegistry {

	/**
	 * Singleton instance.
	 *
	 * @var TriggerRegistry|null
	 */
	private static ?TriggerRegistry $instance = null;

	/**
	 * Get singleton instance.
	 *
	 * @return TriggerRegistry
	 */
	public static function get_instance(): TriggerRegistry {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Get the WordPress action hook name for registration.
	 *
	 * @return string Hook name.
	 */
	protected function get_registration_hook(): string {
		return 'sequensy_register_triggers';
	}

	/**
	 * Get the transient key for metadata caching.
	 *
	 * @return string Transient key.
	 */
	protected function get_transient_key(): string {
		return 'sequensy_trigger_metadata';
	}

	/**
	 * Hook called after a trigger is registered.
	 *
	 * Triggers need to register their WordPress hooks immediately
	 * after being added to the registry.
	 *
	 * @param string $type    Trigger type.
	 * @param object $handler Trigger handler instance.
	 * @return void
	 */
	protected function on_registered( string $type, object $handler ): void {
		if ( $handler instanceof TriggerHandler ) {
			$handler->register();
		}
	}

	/**
	 * Get a trigger handler by type.
	 *
	 * Alias for get() with TriggerHandler return type.
	 *
	 * @param string $type Trigger type identifier.
	 * @return TriggerHandler|null Handler instance or null if not found.
	 */
	public function get_trigger( string $type ): ?TriggerHandler {
		$handler = $this->get( $type );
		return $handler instanceof TriggerHandler ? $handler : null;
	}

	/**
	 * Get all registered triggers.
	 *
	 * Alias for get_all().
	 *
	 * @return array<string, TriggerHandler> Array of trigger handlers keyed by type.
	 */
	public function get_all_triggers(): array {
		return $this->get_all();
	}

	/**
	 * Check if a trigger type is registered.
	 *
	 * Alias for has().
	 *
	 * @param string $type Trigger type identifier.
	 * @return bool True if registered, false otherwise.
	 */
	public function has_trigger( string $type ): bool {
		return $this->has( $type );
	}
}
