<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Commerce\Catalog\Enrollment;

use CpCreation\VitiCore\Commerce\Catalog\Enrollment\Message\DeliverCatalogEnrollmentMessage;
use CpCreation\VitiCore\Commerce\Catalog\Enrollment\Repository\CatalogEnrollmentRequestRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;

final readonly class CatalogEnrollmentFailureSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private CatalogEnrollmentRequestRepository $repository,
        private EntityManagerInterface $entityManager,
    ) {}

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

    public function onWorkerMessageFailed(WorkerMessageFailedEvent $event): void
    {
        $message = $event->getEnvelope()->getMessage();
        if (!$message instanceof DeliverCatalogEnrollmentMessage || $event->willRetry()) {
            return;
        }

        $request = $this->repository->findOneByRequestId($message->requestId);
        if (null === $request || $request->isDeliveryComplete()) {
            return;
        }

        $request->releaseAfterRetriesExhausted(
            new \DateTimeImmutable('now', new \DateTimeZone('UTC')),
            'Cycle de tentatives d’enrôlement épuisé, nouvelle tentative planifiée : ' . $event->getThrowable()->getMessage(),
        );
        $this->entityManager->flush();
    }
}
