<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\EventListener\Workflow;

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Entity\AttendanceStash;
use Ferienpass\CoreBundle\Repository\AttendanceStashRepository;
use Symfony\Component\Workflow\Attribute\AsEnteredListener;
use Symfony\Component\Workflow\Event\EnteredEvent;

#[AsEnteredListener(workflow: 'attendance')]
class AttendanceStashListener
{
    public function __construct(private readonly EntityManagerInterface $entityManager, private readonly AttendanceStashRepository $stashRepository)
    {
    }

    public function __invoke(EnteredEvent $event): void
    {
        $attendance = $event->getSubject();
        if (!$attendance instanceof Attendance) {
            return;
        }

        $context = $event->getContext();
        $commit = $context['commit'] ?? true;

        if ($commit) {
            return;
        }

        if ($attendance->getStash()) {
            return;
        }

        $stash = $this->stashRepository->findOneBy([]);
        $attendance->setStash($stash ?? new AttendanceStash());
    }
}
