<?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\Messenger;

use Chill\MainBundle\Repository\Workflow\EntityWorkflowStepSignatureRepository;
use Chill\MainBundle\Workflow\SignatureStepStateChanger;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

final readonly class PostSignatureStateChangeHandler implements MessageHandlerInterface
{
    public function __construct(
        private EntityWorkflowStepSignatureRepository $entityWorkflowStepSignatureRepository,
        private SignatureStepStateChanger $signatureStepStateChanger,
        private EntityManagerInterface $entityManager,
    ) {}

    public function __invoke(PostSignatureStateChangeMessage $message): void
    {
        $signature = $this->entityWorkflowStepSignatureRepository->find($message->signatureId);

        if (null === $signature) {
            throw new UnrecoverableMessageHandlingException('signature not found');
        }

        $this->entityManager->wrapInTransaction(function () use ($signature) {
            $this->signatureStepStateChanger->onPostMark($signature);

            $this->entityManager->flush();
        });

        $this->entityManager->clear();
    }
}
