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

use Chill\MainBundle\Repository\ExportGenerationRepository;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

#[AsMessageHandler]
final readonly class RemoveExportGenerationMessageHandler implements MessageHandlerInterface
{
    private const LOG_PREFIX = '[RemoveExportGenerationMessageHandler] ';

    public function __construct(
        private ExportGenerationRepository $exportGenerationRepository,
        private EntityManagerInterface $entityManager,
        private LoggerInterface $logger,
        private ClockInterface $clock,
    ) {}

    public function __invoke(RemoveExportGenerationMessage $message): void
    {
        $exportGeneration = $this->exportGenerationRepository->find($message->exportGenerationId);

        if (null === $exportGeneration) {
            $this->logger->error(self::LOG_PREFIX.'ExportGeneration not found');
            throw new UnrecoverableMessageHandlingException(self::LOG_PREFIX.'ExportGeneration not found');
        }

        $storedObject = $exportGeneration->getStoredObject();
        $storedObject->setDeleteAt($this->clock->now());

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