<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\DependencyInjection\Compiler;

use Ferienpass\AdminBundle\Cache\FilterWithTtlRegistry;
use Ferienpass\AdminBundle\Form\Filter\Ttl;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

final class FilterTtlPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        if (!$container->hasDefinition(FilterWithTtlRegistry::class)) {
            return;
        }

        $map = [];
        foreach ($container->findTaggedServiceIds('ferienpass_admin.sub_filter') as $tags) {
            foreach ($tags as $tag) {
                $key = $tag['key'] ?? null;
                $ttlName = $tag['ttl'] ?? null;
                if (!\is_string($key) || !\is_string($ttlName) || '' === $ttlName) {
                    continue;
                }

                $ttl = \constant(Ttl::class.'::'.$ttlName);
                if (!$ttl instanceof Ttl) {
                    continue;
                }

                $views = \is_array($tag['views'] ?? null) ? array_values($tag['views']) : [];
                $map[$key] = ['ttl' => $ttl, 'views' => $views];
            }
        }

        $container->getDefinition(FilterWithTtlRegistry::class)->setArgument('$map', $map);
    }
}
