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

use Ferienpass\CoreBundle\Message\OfferRelaunched;
use Ferienpass\CoreBundle\Message\RelaunchOffer as RelaunchOfferCommand;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\Stamp\DispatchAfterCurrentBusStamp;
use Symfony\Component\Uid\Uuid;

#[AsMessageHandler(bus: 'command.bus')]
class RelaunchOffer
{
    public function __construct(private readonly AttendanceRepository $attendances, private readonly MessageBusInterface $eventBus)
    {
    }

    public function __invoke(RelaunchOfferCommand $command, Uuid $uuid): void
    {
        $attendances = $this->attendances->findConfirmed(Uuid::fromString($command->getOfferId()));

        foreach ($attendances as $attendance) {
            // Restore payability, mirroring CancelOffer which unconditionally
            // unsets it. Without this, a cancel→relaunch cycle would leave the
            // fee permanently non-collectible: the attendance would silently
            // drop out of the unpaid/due lists (PaymentsFacade requires
            // payable <> 0). Guard exactly as AttendanceConfirmTransactionListener
            // does, so we only re-enable it for attendances that were payable to
            // begin with (offer has a fee and accepts online payment).
            $offer = $attendance->getOffer();
            if ($offer->getFee() && $offer->isOnlinePayable()) {
                $attendance->setPayable(true);
            }

            $event = new OfferRelaunched((string) $attendance->getUuid(), (string) $uuid, $command->getNotifyText());
            $this->eventBus->dispatch(
                new Envelope($event)
                    ->with(new DispatchAfterCurrentBusStamp())
            );
        }
    }
}
