<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Mercure\Transport;

use Symfony\Component\Mercure\Exception\InvalidArgumentException;
use Symfony\Component\Mercure\HubRegistry;
use Symfony\Component\Notifier\Exception\IncompleteDsnException;
use Symfony\Component\Notifier\Exception\UnsupportedSchemeException;
use Symfony\Component\Notifier\Transport\AbstractTransportFactory;
use Symfony\Component\Notifier\Transport\Dsn;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

final class MercureCustomTransportFactory extends AbstractTransportFactory
{
    public function __construct(
        private HubRegistry $registry,
        ?EventDispatcherInterface $dispatcher = null,
        ?HttpClientInterface $client = null,
    ) {
        parent::__construct($dispatcher, $client);
    }

    public function create(Dsn $dsn): MercureCustomTransport
    {
        if ('mercure' !== $dsn->getScheme()) {
            throw new UnsupportedSchemeException($dsn, 'mercure', $this->getSupportedSchemes());
        }

        $hubId = $dsn->getHost();
        $topic = $dsn->getOption('topic');

        try {
            $hub = $this->registry->getHub($hubId);
        } catch (InvalidArgumentException) {
            throw new IncompleteDsnException(\sprintf('Hub "%s" not found. Did you mean one of: "%s"?', $hubId, implode('", "', array_keys($this->registry->all()))));
        }

        return new MercureCustomTransport($hub, $hubId, (array) $topic, $this->client, $this->dispatcher);
    }

    protected function getSupportedSchemes(): array
    {
        return ['mercure'];
    }
}
