<?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\Offer\OfferInterface;
use Ferienpass\CoreBundle\Enum\OfferStatus;
use Ferienpass\CoreBundle\Enum\OfferTransition;
use Ferienpass\CoreBundle\Message\RelaunchOffer;
use Ferienpass\CoreBundle\Messenger\UuidStamp;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Workflow\Attribute\AsEnteredListener;
use Symfony\Component\Workflow\Event\EnteredEvent;

#[AsEnteredListener(workflow: 'offer', place: OfferStatus::PUBLISHED)]
class OfferRelaunchTransactionListener
{
    public function __construct(private readonly MessageBusInterface $commandBus)
    {
    }

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

        if (OfferTransition::RELAUNCH !== $event->getTransition()?->getName()) {
            return;
        }

        $context = $event->getContext();
        $uuid = $context['uuid'] ?? null;

        $command = new RelaunchOffer((string) $offer->getUuid(), $context['notifyText'] ?? null);
        $this->commandBus->dispatch(
            new Envelope($command)
                ->with(new UuidStamp($uuid))
        );
    }
}
