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

use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Entity\Offer\Base;
use Ferienpass\CoreBundle\Entity\Participant\BaseParticipant;
use Ferienpass\CoreBundle\Message\CancelOffer as CancelOfferCommand;
use Ferienpass\CoreBundle\MessageHandler\CancelOffer;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Uid\Uuid;

final class CancelOfferTest extends TestCase
{
    public function testDoesNotDispatchWhenNoConfirmedAttendances(): void
    {
        $repo = $this->createMock(AttendanceRepository::class);
        $repo->method('findConfirmed')->willReturn([]);

        $bus = $this->createMock(MessageBusInterface::class);
        $bus->expects(self::never())->method('dispatch');

        $handler = new CancelOffer($repo, $bus);
        $handler(new CancelOfferCommand(Uuid::v7()->toRfc4122()), Uuid::v7());
    }

    public function testSetsPayableFalseAndDispatchesEventPerAttendance(): void
    {
        $offer = new Base();
        $participant = new BaseParticipant();
        $attendance1 = new Attendance($offer, $participant);
        $attendance2 = new Attendance($offer, $participant);

        $idRp = new \ReflectionProperty($attendance1, 'id');
        $idRp->setValue($attendance1, 10);
        $idRp2 = new \ReflectionProperty($attendance2, 'id');
        $idRp2->setValue($attendance2, 11);

        $repo = $this->createMock(AttendanceRepository::class);
        $repo->method('findConfirmed')->willReturn([$attendance1, $attendance2]);

        $bus = $this->createMock(MessageBusInterface::class);
        $bus->expects(self::exactly(2))->method('dispatch')->willReturn(new Envelope(new \stdClass()));

        $handler = new CancelOffer($repo, $bus);
        $handler(new CancelOfferCommand(Uuid::v7()->toRfc4122(), 'Offer cancelled'), Uuid::v7());

        self::assertFalse($attendance1->isPayable());
        self::assertFalse($attendance2->isPayable());
    }
}
