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

use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
use Symfony\Component\Messenger\Event\WorkerMessageHandledEvent;

/**
 * The OnAfterMessageHandledClearStoredObjectCache class is an event subscriber that clears the stored object cache
 * after a specific message is handled or fails.
 */
final readonly class OnAfterMessageHandledClearStoredObjectCache implements EventSubscriberInterface
{
    public function __construct(
        private StoredObjectManagerInterface $storedObjectManager,
        private LoggerInterface $logger,
    ) {}

    public static function getSubscribedEvents()
    {
        return [
            WorkerMessageHandledEvent::class => [
                ['afterHandling', 0],
            ],
            WorkerMessageFailedEvent::class => [
                ['afterFails', 0],
            ],
        ];
    }

    public function afterHandling(WorkerMessageHandledEvent $event): void
    {
        if ($event->getEnvelope()->getMessage() instanceof RequestGenerationMessage) {
            $this->clearStoredObjectCache();
        }
    }

    public function afterFails(WorkerMessageFailedEvent $event): void
    {
        if ($event->getEnvelope()->getMessage() instanceof RequestGenerationMessage) {
            $this->clearStoredObjectCache();
        }
    }

    private function clearStoredObjectCache(): void
    {
        $this->logger->debug('clear the cache after generation of a document');

        $this->storedObjectManager->clearCache();
    }
}
