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

use Chill\CalendarBundle\Entity\CalendarRange;
use Chill\CalendarBundle\Messenger\Message\CalendarRangeMessage;
use Chill\CalendarBundle\Messenger\Message\CalendarRangeRemovedMessage;
use Doctrine\ORM\Event\PostPersistEventArgs;
use Doctrine\ORM\Event\PostRemoveEventArgs;
use Doctrine\ORM\Event\PostUpdateEventArgs;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Security;

class CalendarRangeEntityListener
{
    public function __construct(private readonly MessageBusInterface $messageBus, private readonly Security $security) {}

    public function postPersist(CalendarRange $calendarRange, PostPersistEventArgs $eventArgs): void
    {
        if (!$calendarRange->preventEnqueueChanges) {
            $this->messageBus->dispatch(
                new CalendarRangeMessage(
                    $calendarRange,
                    CalendarRangeMessage::CALENDAR_RANGE_PERSIST,
                    $this->security->getUser()
                )
            );
        }
    }

    public function postRemove(CalendarRange $calendarRange, PostRemoveEventArgs $eventArgs): void
    {
        if (!$calendarRange->preventEnqueueChanges) {
            $this->messageBus->dispatch(
                new CalendarRangeRemovedMessage(
                    $calendarRange,
                    $this->security->getUser()
                )
            );
        }
    }

    public function postUpdate(CalendarRange $calendarRange, PostUpdateEventArgs $eventArgs): void
    {
        if (!$calendarRange->preventEnqueueChanges) {
            $this->messageBus->dispatch(
                new CalendarRangeMessage(
                    $calendarRange,
                    CalendarRangeMessage::CALENDAR_RANGE_UPDATE,
                    $this->security->getUser()
                )
            );
        }
    }
}
