<?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\AttendanceCreated;
use Ferienpass\CoreBundle\Message\AttendanceStatusChanged;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Workflow\Attribute\AsAnnounceListener;
use Symfony\Component\Workflow\Event\AnnounceEvent;

#[AsAnnounceListener(workflow: 'attendance')]
class AttendanceStatusTransactionListener
{
    public function __construct(private readonly MessageBusInterface $eventBus, private readonly RequestStack $requestStack)
    {
    }

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

        // Holding an anonymous application for e-mail confirmation is an internal,
        // invisible step — it neither creates nor changes a real application yet.
        // The confirmation e-mail is dispatched separately by the application form.
        if (AttendanceStatus::EMAIL_UNCONFIRMED === $attendance->getStatus()) {
            return;
        }

        $context = $event->getContext();
        $shallNotify = $context['notify'] ?? true;
        $groupId = $context['group'] ?? null;
        if (\is_string($groupId)) {
            $groupId = Uuid::fromString($groupId);
        }

        if ($context['initial'] ?? false) {
            $host = $this->requestStack->getCurrentRequest()?->getHost();
            $this->eventBus->dispatch(new AttendanceCreated((string) $attendance->getUuid(), $shallNotify, $host, (string) $groupId));

            return;
        }

        if (null === $attendance->getStatus()) {
            return;
        }

        $transition = $event->getTransition();
        $this->eventBus->dispatch(new AttendanceStatusChanged((string) $attendance->getUuid(), $transition->getFroms()[0] ?? null, (string) $attendance->getStatus(), $shallNotify, $groupId?->toRfc4122()));
    }
}
