<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\EventSubscriber;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\EventListener\AuditorCreateSchemaListener as VitiCoreCreateSchemaListener;
use DH\Auditor\Provider\Doctrine\Persistence\Event\CreateSchemaListener as AuditorCreateSchemaListener;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Tools\ToolEvents;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

final readonly class AuditorSchemaToolSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private ManagerRegistry $managerRegistry,
        private VitiCoreCreateSchemaListener $createSchemaListener,
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            ConsoleEvents::COMMAND => ['onConsoleCommand', 1000],
        ];
    }

    public function onConsoleCommand(ConsoleCommandEvent $event): void
    {
        foreach ($this->managerRegistry->getManagers() as $manager) {
            if (!$manager instanceof EntityManagerInterface) {
                continue;
            }

            $eventManager = $manager->getEventManager();
            $hasReplacement = false;
            foreach ($eventManager->getListeners(ToolEvents::postGenerateSchemaTable) as $listener) {
                if ($listener instanceof VitiCoreCreateSchemaListener) {
                    $hasReplacement = true;
                    continue;
                }

                if ($listener instanceof AuditorCreateSchemaListener) {
                    $eventManager->removeEventListener([ToolEvents::postGenerateSchemaTable], $listener);
                }
            }

            if (!$hasReplacement) {
                $eventManager->addEventListener([ToolEvents::postGenerateSchemaTable], $this->createSchemaListener);
            }
        }
    }
}
