<?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\Messenger\PostSendExternalMessage;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Workflow\Event\CompletedEvent;
use Symfony\Component\Workflow\Registry;
use Symfony\Contracts\Translation\LocaleAwareInterface;

class EntityWorkflowPrepareEmailOnSendExternalEventSubscriber implements EventSubscriberInterface, LocaleAwareInterface
{
    private string $locale;

    public function __construct(private readonly Registry $registry, private readonly MessageBusInterface $messageBus) {}

    public static function getSubscribedEvents(): array
    {
        return [
            'workflow.completed' => 'onWorkflowCompleted',
        ];
    }

    public function onWorkflowCompleted(CompletedEvent $event): void
    {
        $entityWorkflow = $event->getSubject();

        if (!$entityWorkflow instanceof EntityWorkflow) {
            return;
        }

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

        $mustSend = false;
        foreach ($event->getTransition()->getTos() as $to) {
            $metadata = $store->getPlaceMetadata($to);
            if ($metadata['isSentExternal'] ?? false) {
                $mustSend = true;
            }
        }

        if ($mustSend) {
            $this->messageBus->dispatch(new PostSendExternalMessage($entityWorkflow->getId(), $this->getLocale()));
        }
    }

    public function setLocale(string $locale): void
    {
        $this->locale = $locale;
    }

    public function getLocale(): string
    {
        return $this->locale;
    }
}
