<?php declare(strict_types=1);
/**
 * @package messenger
 * @author kputyr
 * @date 17.04.2025
 */

namespace IMATHUZH\Messenger;

use Psr\Log\LoggerAwareTrait;

/**
 * @inheritdoc
 */
class MessageDispatcher implements MessageDispatcherInterface
{
    use LoggerAwareTrait;

    /**
     * @var MessagePublisherInterface[] an internal list of publishers
     */
    protected $publishers = [];

    /**
     * @inheritdoc
     */
    public function addPublisher(MessagePublisherInterface $publisher): self
    {
        $this->publishers[] = $publisher;
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function publishMessage(array $channels, string $name, mixed $payload): array
    {
        $msg = json_encode([
            'type' => 'message',
            'name' => $name,
            'payload' => $payload
        ]);
        $errors = [];
        foreach ($this->publishers as $publisher) {
            foreach ($publisher->publishMessage($channels, $msg) as $key => $error) {
                if (isset($this->logger)) {
                    $this->logger->error("$error: $key", [
                        'publisher' => $publisher::class,
                        'key' => $key
                    ]);
                }
                $errors[] = new MessagePublisherError(
                    $publisher, $key, $error
                );
            }
        }
        return $errors;
    }
}
