<?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\Workflow;

use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;
use Ferienpass\CoreBundle\Entity\OfferDate;
use Ferienpass\CoreBundle\Enum\AttendanceTransition;
use Ferienpass\CoreBundle\Settings\SystemSettingsManager;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Workflow\Attribute\AsGuardListener;
use Symfony\Component\Workflow\Event\GuardEvent;

class AttendanceGuard
{
    public function __construct(private readonly Security $security, private readonly SystemSettingsManager $systemSettingsManager, private readonly CompulsoryWithdrawalContext $compulsoryWithdrawal)
    {
    }

    #[AsGuardListener('attendance', transition: AttendanceTransition::WITHDRAW)]
    public function withdraw(GuardEvent $event): void
    {
        $attendance = $event->getSubject();
        if (!$attendance instanceof Attendance) {
            throw new \RuntimeException();
        }

        $now = new \DateTimeImmutable();
        $offer = $attendance->getOffer();

        if ($this->security->isGranted('ROLE_ADMIN')) {
            return;
        }

        if ($offer->isCancelled()) {
            $event->setBlocked(true);

            return;
        }

        $offerDate = $offer->getDates()->first();
        if ($offerDate instanceof OfferDate && $now > $offerDate->getBegin()) {
            $event->setBlocked(true);

            return;
        }

        // Revoking a compulsory consent mandates this withdrawal: the
        // organiser's convenience guards below (no-withdraw-after-deadline /
        // -grace-period) do not apply to a compliance-driven cancellation. The
        // cancelled / already-started guards above still do.
        if ($this->compulsoryWithdrawal->isActive()) {
            return;
        }

        $afterDeadline = $this->systemSettingsManager->isNoWithdrawAfterApplicationDeadline() && $offer->getApplicationDeadline() && $now > $offer->getApplicationDeadline();
        $afterGracePeriod = $this->systemSettingsManager->isNoWithdrawAfterGracePeriod() && !$this->inGracePeriod($offer);

        // A "Sofortstornierung" corrects a spot the family got minutes ago, so both
        // convenience rules step aside: without this, someone confirmed for an offer
        // that starts within the grace period (or after the deadline has passed)
        // could not hand it back at all — and would be charged for it. Asked last
        // because it reads the activity log, which only a blocked withdrawal needs.
        if (($afterDeadline || $afterGracePeriod) && !$attendance->isInstantWithdrawal($now)) {
            $event->setBlocked(true);
        }
    }

    private function inGracePeriod(OfferInterface $offer): bool
    {
        $gracePeriodStr = $this->systemSettingsManager->getWithdrawGracePeriod();
        $gracePeriod = $gracePeriodStr ? new \DateTimeImmutable($gracePeriodStr) : null;

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