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

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Exception\StoredObjectManagerException;
use Chill\DocStoreBundle\Repository\StoredObjectVersionRepository;
use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

/**
 * Class RemoveOldVersionMessageHandler.
 *
 * This class is responsible for handling the RemoveOldVersionMessage. It implements the MessageHandlerInterface.
 * It removes old versions of stored objects based on certain conditions.
 *
 * If a StoredObject is a candidate for deletion (is expired and no more version stored), it is also removed from the
 * database.
 */
final readonly class RemoveOldVersionMessageHandler implements MessageHandlerInterface
{
    private const LOG_PREFIX = '[RemoveOldVersionMessageHandler] ';

    public function __construct(
        private StoredObjectVersionRepository $storedObjectVersionRepository,
        private LoggerInterface $logger,
        private EntityManagerInterface $entityManager,
        private StoredObjectManagerInterface $storedObjectManager,
        private ClockInterface $clock,
    ) {}

    /**
     * @throws StoredObjectManagerException
     */
    public function __invoke(RemoveOldVersionMessage $message): void
    {
        $this->logger->info(self::LOG_PREFIX.'Received one message', ['storedObjectVersionId' => $message->storedObjectVersionId]);

        $storedObjectVersion = $this->storedObjectVersionRepository->find($message->storedObjectVersionId);

        if (null === $storedObjectVersion) {
            $this->logger->error(self::LOG_PREFIX.'StoredObjectVersion not found in database', ['storedObjectVersionId' => $message->storedObjectVersionId]);
            throw new \RuntimeException('StoredObjectVersion not found with id '.$message->storedObjectVersionId);
        }

        if ($storedObjectVersion->hasPointInTimes()) {
            throw new UnrecoverableMessageHandlingException('the stored object version is now associated with a point in time');
        }

        $storedObject = $storedObjectVersion->getStoredObject();

        if ($this->storedObjectManager->exists($storedObjectVersion)) {
            $this->storedObjectManager->delete($storedObjectVersion);
        } else {
            $this->logger->notice(
                self::LOG_PREFIX.'Stored object version does not exists any more.',
                ['storedObjectVersionName' => $storedObjectVersion->getFilename()],
            );
        }

        // to ensure an immediate deletion
        $this->entityManager->remove($storedObjectVersion);

        if (StoredObject::canBeDeleted($this->clock->now(), $storedObject)) {
            $this->entityManager->remove($storedObject);
        }

        $this->entityManager->flush();

        // clear the entity manager for future usage
        $this->entityManager->clear();
    }
}
