<?php
declare(strict_types=1);

namespace App\Core\Events;

use App\Core\Logging\FileLogger;

final class EventBus
{
    /** @var array<string,list<callable>> */
    private array $listeners = [];

    public function __construct(private readonly ?FileLogger $logger = null)
    {
    }

    public function listen(string $event, callable $listener): void
    {
        $this->listeners[$event][] = $listener;
    }

    /** @param array<string,mixed> $payload */
    public function dispatch(string $event, array $payload = []): void
    {
        $this->logger?->info('event.dispatched', ['event' => $event, 'listeners' => count($this->listeners[$event] ?? [])]);
        foreach ($this->listeners[$event] ?? [] as $listener) {
            $listener($payload, $event);
        }
    }

    /** @return array<string,int> */
    public function summary(): array
    {
        $result = [];
        foreach ($this->listeners as $event => $listeners) {
            $result[$event] = count($listeners);
        }
        ksort($result);
        return $result;
    }
}
