<?php
/**
 * سودانا — EventBus v3
 * emit() → QueueEngine only (no sync dispatch = no double execution)
 * Fallback to sync subscribers if queue is unavailable.
 */
class EventBus {

    private static array $handlers = [];

    public static function subscribe(string $event, callable $handler): void {
        self::$handlers[$event][] = $handler;
    }

    public static function emit(string $event, array $payload): string {
        $eventId = uniqid('evt_', true);
        try {
            QueueEngine::enqueue('event', array_merge($payload, [
                'event'    => $event,
                'event_id' => $eventId,
            ]), null, $eventId);
        } catch (Throwable $e) {
            error_log("[EventBus] Queue unavailable, sync fallback for '$event': " . $e->getMessage());
            foreach (self::$handlers[$event] ?? [] as $handler) {
                try { call_user_func($handler, $event, $payload); }
                catch (Throwable $he) { error_log("[EventBus::sync] " . $he->getMessage()); }
            }
        }
        return $eventId;
    }
}
