<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Workflow\EventSubscriber;

use Chill\MainBundle\Entity\Workflow\EntityWorkflow;
use Chill\MainBundle\Workflow\EntityWorkflowManager;
use Chill\MainBundle\Workflow\EntityWorkflowWithPublicViewInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Workflow\Event\GuardEvent;
use Symfony\Component\Workflow\Registry;
use Symfony\Component\Workflow\TransitionBlocker;

final readonly class EntityWorkflowGuardSendExternalIfNoPublicView implements EventSubscriberInterface
{
    public function __construct(private Registry $registry, private EntityWorkflowManager $entityWorkflowManager) {}

    public static function getSubscribedEvents()
    {
        return ['workflow.guard' => [
            ['guardSendExternalIfNoStoredObject', 0],
        ]];
    }

    public function guardSendExternalIfNoStoredObject(GuardEvent $event)
    {
        $entityWorkflow = $event->getSubject();
        if (!$entityWorkflow instanceof EntityWorkflow) {
            return;
        }

        $workflow = $this->registry->get($entityWorkflow, $entityWorkflow->getWorkflowName());

        foreach ($event->getTransition()->getTos() as $to) {
            $metadata = $workflow->getMetadataStore()->getPlaceMetadata($to);
            if (true === ($metadata['isSentExternal'] ?? false)
                && !$this->entityWorkflowManager->getHandler($entityWorkflow) instanceof EntityWorkflowWithPublicViewInterface) {
                $event->addTransitionBlocker(
                    new TransitionBlocker(
                        'No document associated with this entityWorkflow, not able to send external',
                        'a95e57d8-9136-11ef-a208-43b111cfc66d'
                    )
                );

                return;
            }
        }
    }
}
