<?php
declare(strict_types=1);

namespace Celena\Core\Plugin;

/**
 * Хуки в стиле WordPress: action (только эффект) и filter (преобразование значения).
 * Используется ядром во всех ключевых точках. Плагины подписываются в plugin.php.
 */
final class Hook
{
    /** @var array<string, array<int, list<callable>>> */
    private static array $actions = [];

    /** @var array<string, array<int, list<callable>>> */
    private static array $filters = [];

    public static function on(string $event, callable $callback, int $priority = 10): void
    {
        self::$actions[$event][$priority][] = $callback;
    }

    public static function filter(string $event, mixed $value, mixed ...$args): mixed
    {
        if (!isset(self::$filters[$event])) {
            return $value;
        }
        $byPriority = self::$filters[$event];
        ksort($byPriority);
        foreach ($byPriority as $callbacks) {
            foreach ($callbacks as $cb) {
                $value = $cb($value, ...$args);
            }
        }
        return $value;
    }

    public static function addFilter(string $event, callable $callback, int $priority = 10): void
    {
        self::$filters[$event][$priority][] = $callback;
    }

    public static function action(string $event, mixed ...$args): void
    {
        if (!isset(self::$actions[$event])) {
            return;
        }
        $byPriority = self::$actions[$event];
        ksort($byPriority);
        foreach ($byPriority as $callbacks) {
            foreach ($callbacks as $cb) {
                $cb(...$args);
            }
        }
    }

    public static function reset(): void
    {
        self::$actions = [];
        self::$filters = [];
    }
}
