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

use CpCreation\VitiCore\Commerce\Catalog\Outbox\Message\DeliverCatalogChangeMessage;
use CpCreation\VitiCore\Commerce\Catalog\Repository\CatalogChangeRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;

/**
 * Ferme l'état de livraison une fois les retries Messenger épuisés. Les claims
 * QUEUED sans aucune consommation restent, eux, récupérables par le scheduler.
 */
final readonly class CatalogDeliveryFailureSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private CatalogChangeRepository $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 DeliverCatalogChangeMessage || $event->willRetry()) {
            return;
        }

        $change = $this->repository->findOneByEventId($message->eventId);
        if (null === $change || $change->isDeliveryComplete()) {
            return;
        }

        $change->markRetriesExhausted(
            new \DateTimeImmutable(),
            'Tentatives webhook épuisées : ' . $event->getThrowable()->getMessage(),
        );
        $this->entityManager->flush();
    }
}
