<?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\DocStoreBundle\Service\Signature\Driver\BaseSigner;

use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
use Chill\MainBundle\Repository\Workflow\EntityWorkflowStepSignatureRepository;
use Chill\MainBundle\Workflow\EntityWorkflowManager;
use Chill\MainBundle\Workflow\SignatureStepStateChanger;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

final readonly class PdfSignedMessageHandler implements MessageHandlerInterface
{
    /**
     * log prefix.
     */
    private const P = '[pdf signed message] ';

    public function __construct(
        private LoggerInterface $logger,
        private EntityWorkflowManager $entityWorkflowManager,
        private StoredObjectManagerInterface $storedObjectManager,
        private EntityWorkflowStepSignatureRepository $entityWorkflowStepSignatureRepository,
        private EntityManagerInterface $entityManager,
        private SignatureStepStateChanger $signatureStepStateChanger,
    ) {}

    public function __invoke(PdfSignedMessage $message): void
    {
        $this->logger->info(self::P.'a message is received', ['signaturedId' => $message->signatureId]);

        $signature = $this->entityWorkflowStepSignatureRepository->find($message->signatureId);

        if (null === $signature) {
            throw new \RuntimeException('no signature found');
        }

        $storedObject = $this->entityWorkflowManager->getAssociatedStoredObject($signature->getStep()->getEntityWorkflow());

        if (null === $storedObject) {
            throw new \RuntimeException('no stored object found');
        }

        $this->entityManager->wrapInTransaction(function () use ($storedObject, $message, $signature) {
            $this->storedObjectManager->write($storedObject, $message->content);
            $this->signatureStepStateChanger->markSignatureAsSigned($signature, $message->signatureZoneIndex);
        });

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