<?php
declare(strict_types=1);

namespace App\Core;

final class EventBus
{
    private static array $listeners = [];

    public static function listen(string $event, callable $handler, int $priority = 0): void
    {
        self::$listeners[$event][] = [
            'handler'  => $handler,
            'priority' => $priority,
        ];
    }

    public static function dispatch(string $event, array $data = []): array
    {
        if (!isset(self::$listeners[$event])) {
            return [];
        }

        $sorted = self::$listeners[$event];
        usort($sorted, fn($a, $b) => $b['priority'] <=> $a['priority']);

        $results = [];
        foreach ($sorted as $listener) {
            $result = ($listener['handler'])($data);
            if ($result !== null) {
                $results[] = $result;
            }
        }

        return $results;
    }

    public static function hasListeners(string $event): bool
    {
        return !empty(self::$listeners[$event]);
    }

    public static function getListeners(string $event): array
    {
        return self::$listeners[$event] ?? [];
    }

    public static function clearListeners(string $event): void
    {
        unset(self::$listeners[$event]);
    }

    public static function dispatchAsync(string $event, array $data = []): void
    {
        try {
            $db = App::getInstance()->db();
            $db->insert('async_event_queue', [
                'event_name'     => $event,
                'event_data_json' => json_encode($data, JSON_UNESCAPED_UNICODE),
                'status'         => 'pending',
                'attempts'       => 0,
                'max_attempts'   => 3,
                'created_at'     => date('Y-m-d H:i:s'),
            ]);
        } catch (\Exception $e) {
            Logger::error('Failed to queue async event: ' . $e->getMessage(), ['event' => $event]);
        }
    }
}