<?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 Serenity\CoreBundle\Shared\Twig\Extensions;

use Doctrine\ORM\EntityManagerInterface;
use Serenity\CoreBundle\Config\Repository\ConfigRepository;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class ConfigExtension extends AbstractExtension
{
    public function __construct(
        private ConfigRepository $configRepository,
        private readonly EntityManagerInterface $em,
        #[Autowire('%serenity_saas%')]
        private readonly bool $saasEnabled = false,
    ) {
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('config', $this->getConfig(...)),
        ];
    }

    public function getConfig(string $name, bool $disableSerenityIdentifier = false): ?object
    {
        if ($disableSerenityIdentifier && $this->saasEnabled) {
            if ($this->em->getFilters()->isEnabled('serenity_saas_filter')) {
                $this->em->getFilters()->disable('serenity_saas_filter');
            }
        }
        $config = $this->configRepository->findOne($name);
        if ($this->saasEnabled) {
            $this->em->getFilters()->enable('serenity_saas_filter');
        }

        if (null === $config) {
            return null;
        }

        return $config->getValue();
    }
}
