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

use Chill\TicketBundle\Event\PostTicketUpdateEvent;
use Chill\TicketBundle\Messenger\PostTicketUpdateMessage;
use Chill\TicketBundle\Repository\TicketRepositoryInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

#[AsMessageHandler]
final readonly class PostTicketUpdateMessageHandler implements MessageHandlerInterface
{
    public function __construct(
        private EventDispatcherInterface $eventDispatcher,
        private TicketRepositoryInterface $ticketRepository,
    ) {}

    public function __invoke(PostTicketUpdateMessage $event): void
    {
        $ticket = $this->ticketRepository->find($event->ticketId);

        if (null === $ticket) {
            throw new UnrecoverableMessageHandlingException('Ticket not found');
        }

        $this->eventDispatcher->dispatch(new PostTicketUpdateEvent($event->updateKind, $ticket));
    }
}
