<?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 Ferienpass\CoreBundle\Settings\SystemSettingsManager;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Workflow\Attribute\AsEnteredListener;
use Symfony\Component\Workflow\Event\EnteredEvent;

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

    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;

        // Withdrawing after the grace period keeps the liability — except when the
        // family cancels right after registering ("Sofortstornierung"), where no
        // spot was ever kept from anyone.
        if ($this->isInGracePeriod($attendance) || $attendance->isInstantWithdrawal()) {
            $attendance->setPayable(false);
        }

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

    /**
     * Read through the settings manager, not from the container parameter: the
     * grace period is an admin-editable setting ({@see \Ferienpass\CoreBundle\Entity\PageConfig}),
     * and reading only the (usually unset) parameter silently waived every fee.
     */
    private function isInGracePeriod(Attendance $attendance): bool
    {
        $gracePeriodStr = $this->systemSettingsManager->getWithdrawGracePeriod();
        $gracePeriod = $gracePeriodStr ? new \DateTimeImmutable($gracePeriodStr) : null;

        return !$gracePeriod instanceof \DateTimeImmutable || ($attendance->getOffer()->getDates()->isEmpty() || $attendance->getOffer()->getDates()->first()->getBegin() > $gracePeriod);
    }
}
