<?php

declare(strict_types=1);

namespace NoahVet\Reef\RabbitMQ;

use PhpAmqpLib\Connection\AbstractConnection;
use PhpAmqpLib\Connection\AMQPConnectionConfig;
use PhpAmqpLib\Connection\AMQPConnectionFactory;

class RabbitMQConnectionFactory implements RabbitMQConnectionFactoryInterface
{
    protected ?AbstractConnection $connection = null;

    public function __construct(
        private readonly string $rabbitMQUrl,
        private readonly string $reefServiceToken,
    ) {
    }

    public function get(): AbstractConnection
    {
        if (null === $this->connection) {
            $urlParts = \parse_url($this->rabbitMQUrl);

            if (!\is_array($urlParts)) {
                throw new \Exception('Invalid RabbitMQ Url');
            }

            $config = new AMQPConnectionConfig();
            $config->setHost($urlParts['host'] ?? '');
            $config->setPort($urlParts['port'] ?? 5672);
            $config->setVhost(\substr($urlParts['path'] ?? '/reef', 1));
            $config->setLoginMethod(AMQPConnectionConfig::AUTH_PLAIN);
            $config->setUser('oauth');
            $config->setPassword($this->reefServiceToken);
            $config->setLocale('fr_FR');

            $this->connection = AMQPConnectionFactory::create($config);
        }

        return $this->connection;
    }
}
