<?php

namespace NoahVet\Reef\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension;

class ReefApiClientExtension extends ConfigurableExtension
{
    #[\Override]
    public function getAlias(): string
    {
        return 'reef';
    }

    /**
     * @param array<array-key, mixed> $mergedConfig
     */
    #[\Override]
    protected function loadInternal(array $mergedConfig, ContainerBuilder $container): void
    {
        $container->setParameter('reef.app_name', $mergedConfig['app_name']);
        $container->setParameter('reef.url', $mergedConfig['url']);
        $container->setParameter('reef.oauth_base_url', $mergedConfig['oauth_base_url']);
        $container->setParameter('reef.client_id', $mergedConfig['client_id']);
        $container->setParameter('reef.client_secret', $mergedConfig['client_secret']);
        $container->setParameter('reef.service_token', $mergedConfig['service_token']);
        $container->setParameter('reef.cache_service', $mergedConfig['cache_service']);
        $container->setParameter('reef.http_cache_service', $mergedConfig['http_cache_service']);
        $container->setParameter('reef.log_url', $mergedConfig['log_url']);
        $container->setParameter('reef.rabbitmq_url', $mergedConfig['rabbitmq_url']);

        $env = $container->hasParameter('kernel.environment')
            ? $container->getParameter('kernel.environment')
            : null;

        $loader = new YamlFileLoader(
            $container,
            new FileLocator(__DIR__.'/../Resources/config'),
            \is_string($env) ? $env : null,
        );
        $loader->load('services.yaml');

        if (!empty($mergedConfig['service_token'])) {
            $loader->load('services_servicetoken.yaml');
        }
    }
}
