<?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\Routing;

use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\RouteCollection;

class BundleLoader extends Loader
{
    public function __construct(private readonly KernelInterface $kernel)
    {
        parent::__construct($this->kernel->getEnvironment());
    }

    public function load(mixed $resource, ?string $type = null): RouteCollection
    {
        $routes = new RouteCollection();

        foreach ($this->kernel->getBundles() as $bundle) {
            if (str_starts_with($bundle->getName(), 'Serenity')) {
                try {
                    $resource = $this->kernel->locateResource('@'.$bundle->getName().'/config/routes.yaml');
                    $importedRoutes = $this->import($resource, 'yaml');
                    $routes->addCollection($importedRoutes);
                } catch (\InvalidArgumentException $e) {
                }
            }
        }

        return $routes;
    }

    public function supports($resource, ?string $type = null): bool
    {
        return 'bundle_extra' === $type;
    }
}
