<?php

declare(strict_types=1);

namespace App\Module\ProjectManagement\Infrastructure\EventListener;

use App\Module\ProjectManagement\Domain\Entity\Workflow;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;

#[AsDoctrineListener(event: Events::onFlush)]
final class UniqueDefaultWorkflowListener
{
    public function onFlush(OnFlushEventArgs $args): void
    {
        $em  = $args->getObjectManager();
        $uow = $em->getUnitOfWork();

        $candidates = [];
        foreach ($uow->getScheduledEntityInsertions() as $entity) {
            if ($entity instanceof Workflow && $entity->isDefault()) {
                $candidates[] = $entity;
            }
        }
        foreach ($uow->getScheduledEntityUpdates() as $entity) {
            if ($entity instanceof Workflow && $entity->isDefault()) {
                $candidates[] = $entity;
            }
        }

        if (0 === count($candidates)) {
            return;
        }

        $metadata = $em->getClassMetadata(Workflow::class);
        $repo     = $em->getRepository(Workflow::class);
        foreach ($repo->findBy(['isDefault' => true]) as $existing) {
            if (in_array($existing, $candidates, true)) {
                continue;
            }
            $existing->setIsDefault(false);
            $uow->recomputeSingleEntityChangeSet($metadata, $existing);
        }
    }
}
