<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\TicketBundle\tests\Event\EventSubscriber;

use Chill\TicketBundle\Entity\Ticket;
use Chill\TicketBundle\Event\EventSubscriber\GeneratePostUpdateTicketEventSubscriber;
use Chill\TicketBundle\Event\TicketUpdateEvent;
use Chill\TicketBundle\Event\TicketUpdateKindEnum;
use Chill\TicketBundle\Messenger\PostTicketUpdateMessage;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;

/**
 * @covers \Chill\TicketBundle\Event\EventSubscriber\GeneratePostUpdateTicketEventSubscriber
 *
 * @internal
 */
class GeneratePostUpdateTicketEventSubscriberTest extends TestCase
{
    use ProphecyTrait;

    public function testOnTicketUpdate(): void
    {
        $ticket = new Ticket();
        $reflection = new \ReflectionClass(Ticket::class);
        $idProperty = $reflection->getProperty('id');
        $idProperty->setValue($ticket, 1);
        $event = new class (TicketUpdateKindEnum::UPDATE_MOTIVE, $ticket) extends TicketUpdateEvent {};

        $messageBus = $this->prophesize(MessageBusInterface::class);
        $messageBus->dispatch(Argument::that(fn ($arg) => $arg instanceof PostTicketUpdateMessage && TicketUpdateKindEnum::UPDATE_MOTIVE === $arg->updateKind && 1 === $arg->ticketId))
            ->will(fn ($args) => new Envelope($args[0]))
            ->shouldBeCalled();

        $eventSubscriber = new GeneratePostUpdateTicketEventSubscriber($messageBus->reveal());
        $eventSubscriber->onTicketUpdate($event);

        $kernel = $this->prophesize(KernelInterface::class);
        $terminate = new TerminateEvent($kernel->reveal(), new Request(), new Response());
        $eventSubscriber->onKernelTerminate($terminate);
    }
}
