<?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 Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Enum\AttendanceStatus;
use Ferienpass\CoreBundle\Message\WithdrawAttendance;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Workflow\Attribute\AsEnteredListener;
use Symfony\Component\Workflow\Event\EnteredEvent;

#[AsEnteredListener(workflow: 'attendance', place: AttendanceStatus::UNFULFILLED)]
class AttendanceUnfulfilledTransactionListener
{
    public function __construct(private readonly MessageBusInterface $commandBus)
    {
    }

    public function __invoke(EnteredEvent $event): void
    {
        $attendance = $event->getSubject();
        if (!$attendance instanceof Attendance) {
            throw new \RuntimeException('Unexpected event subject');
        }

        $context = $event->getContext();
        $shallReorder = $context['reorder'] ?? true;
        $shallNotify = $context['notify'] ?? true;

        $attendance->setPayable(false);

        $command = new WithdrawAttendance((string) $attendance->getUuid(), $shallReorder, $shallNotify);
        $this->commandBus->dispatch($command);
    }
}
