<?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\AuthBundle\DependencyInjection;

use Serenity\CoreBundle\Shared\Common\UserInterface;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

class SerenityAuthExtension extends Extension implements PrependExtensionInterface
{
    public function load(array $configs, ContainerBuilder $container): void
    {
        // Charge la config définie dans Configuration.php
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);
        // Paramètre accessible partout
        $container->setParameter('serenity_auth.user_class', $config['user_class']);
        // Charge les services
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../../config'));
        $loader->load('services.yaml');
    }

    public function prepend(ContainerBuilder $container): void
    {
        // 1. Charger les fichiers YAML dans packages/auto/
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../../config/packages/auto'));
        $files = glob(__DIR__.'/../../config/packages/auto/*.yaml') ?: [];
        foreach ($files as $file) {
            $loader->load(basename($file));
        }

        // 2. Optionnel : charger le fichier de sécurité alternatif si SerenitySaasBundle n’est pas présent
        $bundles = $container->getParameter('kernel.bundles');
        if (!\array_key_exists('SerenitySaasBundle', $bundles)) {
            $dir = __DIR__.'/../../config/packages/manual';
            $loader = new YamlFileLoader($container, new FileLocator($dir));
            $loader->load('security.yaml');
            $env = (string) $container->getParameter('kernel.environment');
            $envFile = $env.'/security.yaml';
            if (is_file($dir.'/'.$envFile)) {
                $loader->load($envFile);
            }
        }

        // 3. Fusionner la config de ton bundle
        $configs = $container->getExtensionConfig('serenity_auth');
        $configuration = new Configuration();
        $mergedConfig = (new Processor())->processConfiguration($configuration, $configs);
        // 4. Injecter le mapping Doctrine conditionnel
        $container->prependExtensionConfig('doctrine', [
            'orm' => [
                'resolve_target_entities' => [
                    UserInterface::class => $mergedConfig['user_class'],
                    \Symfony\Component\Security\Core\User\UserInterface::class => $mergedConfig['user_class'],
                ],
            ],
        ]);
        if (($mergedConfig['user_class'] ?? null) === 'Serenity\AuthBundle\Domain\User\Model\User') {
            $container->prependExtensionConfig('doctrine', [
                'orm' => [
                    'mappings' => [
                        'SerenityAuthModel' => [
                            'is_bundle' => false,
                            'type' => 'attribute',
                            'dir' => realpath(__DIR__.'/../Domain/User/Model'),
                            'prefix' => 'Serenity\AuthBundle\Domain\User\Model',
                        ],
                    ],
                ],
            ]);
        }
        $container->setParameter('serenity_auth.user_class', $mergedConfig['user_class']);
    }
}
