<?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\MainBundle\Notification\EventListener;

use Chill\MainBundle\Notification\NotificationPersisterInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\TerminateEvent;

class PersistNotificationOnTerminateEventSubscriber implements EventSubscriberInterface
{
    public function __construct(private readonly EntityManagerInterface $em, private readonly NotificationPersisterInterface $persister) {}

    public static function getSubscribedEvents()
    {
        return [
            'kernel.terminate' => [
                ['onKernelTerminate', 1024], // we must ensure that the priority is before sending email
            ],
        ];
    }

    public function onKernelTerminate(TerminateEvent $event): void
    {
        if ($event->isMainRequest()) {
            $this->persistNotifications();
        }
    }

    private function persistNotifications(): void
    {
        if (0 < \count($this->persister->getWaitingNotifications())) {
            foreach ($this->persister->getWaitingNotifications() as $notification) {
                $this->em->persist($notification);
            }

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