<?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\Offer\OfferInterface;
use Ferienpass\CoreBundle\Entity\OfferDate;
use Ferienpass\CoreBundle\Enum\OfferTransition;
use Symfony\Component\Workflow\Attribute\AsGuardListener;
use Symfony\Component\Workflow\Event\GuardEvent;

class OfferGuard
{
    #[AsGuardListener('offer', transition: OfferTransition::CANCEL)]
    public function cancel(GuardEvent $event): void
    {
        $offer = $event->getSubject();
        if (!$offer instanceof OfferInterface) {
            throw new \RuntimeException();
        }

        if (!$this->isImmutable($offer)
            && $offer->isPublished()
            && !$offer->isCancelled()) {
            return;
        }

        $event->setBlocked(true);
    }

    #[AsGuardListener('offer', transition: OfferTransition::RELAUNCH)]
    public function relaunch(GuardEvent $event): void
    {
        $offer = $event->getSubject();
        if (!$offer instanceof OfferInterface) {
            throw new \RuntimeException();
        }

        if (!$this->isImmutable($offer)
        && $offer->isCancelled()) {
            return;
        }

        $event->setBlocked(true);
    }

    #[AsGuardListener('offer', transition: OfferTransition::COMPLETE)]
    public function complete(GuardEvent $event): void
    {
        $offer = $event->getSubject();
        if (!$offer instanceof OfferInterface) {
            throw new \RuntimeException();
        }

        $date = $offer->getDates()->last();
        if ($offer->isCompleted() || false === $date || $date->getEnd() > new \DateTimeImmutable() || $offer->isDraft() || $offer->isFinalized() || $offer->isReviewed()) {
            $event->setBlocked(true);
        }
    }

    #[AsGuardListener('offer', transition: OfferTransition::APPROVE)]
    public function approve(GuardEvent $event): void
    {
        $offer = $event->getSubject();
        if (!$offer instanceof OfferInterface) {
            throw new \RuntimeException();
        }

        if (!$offer->isCompleted()) {
            return;
        }

        $event->setBlocked(true);
    }

    private function isImmutable(OfferInterface $offer): bool
    {
        if ($offer->isCompleted()) {
            return true;
        }

        if ($offer->getDates()->isEmpty()) {
            return false;
        }

        /** @var OfferDate $date */
        $date = $offer->getDates()->last();

        return (new \DateTimeImmutable()) >= $date->getEnd();
    }
}
