<?php

/**
 * 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.
 */

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

use Chill\CalendarBundle\Messenger\Message\CalendarRangeMessage;
use Chill\CalendarBundle\RemoteCalendar\Connector\RemoteCalendarConnectorInterface;
use Chill\CalendarBundle\Repository\CalendarRangeRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

/**
 * Write calendar range creation / update to the remote calendar.
 *
 * @AsMessageHandler
 */
class CalendarRangeToRemoteHandler implements MessageHandlerInterface
{
    public function __construct(private readonly CalendarRangeRepository $calendarRangeRepository, private readonly RemoteCalendarConnectorInterface $remoteCalendarConnector, private readonly EntityManagerInterface $entityManager) {}

    public function __invoke(CalendarRangeMessage $calendarRangeMessage): void
    {
        $range = $this->calendarRangeRepository->find($calendarRangeMessage->getCalendarRangeId());

        if (null === $range) {
            return;
        }

        $this->remoteCalendarConnector->syncCalendarRange($range);
        $range->preventEnqueueChanges = true;

        $this->entityManager->flush();
    }
}
