<?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\TicketBundle\Event\EventSubscriber;

use Chill\TicketBundle\Event\TicketUpdateEvent;
use Chill\TicketBundle\Messenger\PostTicketUpdateMessage;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Messenger\MessageBusInterface;

/**
 * Subscribe to TicketUpdateEvents and dispatch a message for each one when the kernel terminates.
 */
final class GeneratePostUpdateTicketEventSubscriber implements EventSubscriberInterface
{
    /**
     * @var list<PostTicketUpdateMessage>
     */
    private array $toDispatch = [];

    public function __construct(private readonly MessageBusInterface $messageBus) {}

    public static function getSubscribedEvents(): array
    {
        return [
            TicketUpdateEvent::class => ['onTicketUpdate', 0],
            KernelEvents::TERMINATE => ['onKernelTerminate', 8096],
        ];
    }

    public function onTicketUpdate(TicketUpdateEvent $event): void
    {
        $this->toDispatch[] = new PostTicketUpdateMessage($event->ticket, $event->updateKind);
    }

    public function onKernelTerminate(TerminateEvent $event): void
    {
        foreach ($this->toDispatch as $message) {
            $this->messageBus->dispatch($message);
        }
    }
}
