<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Tests\Messenger;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Messenger\DeduplicateNotificationMiddleware;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Notification\Command\NotificationCommand;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Middleware\StackInterface;

final class DeduplicateNotificationMiddlewareTest extends TestCase
{
    public function testItDeduplicatesNotificationsDispatchedFromSubRequestsOfTheSameMainRequest(): void
    {
        $requestStack = new RequestStack();
        $requestStack->push(Request::create('/_components/cart:ItemForm/_batch'));

        $nextMiddleware = $this->createMock(MiddlewareInterface::class);
        $nextMiddleware
            ->expects(self::once())
            ->method('handle')
            ->willReturnCallback(static fn (Envelope $envelope): Envelope => $envelope);

        $stack = $this->createStub(StackInterface::class);
        $stack
            ->method('next')
            ->willReturn($nextMiddleware);

        $middleware = new DeduplicateNotificationMiddleware($requestStack);

        $requestStack->push(Request::create('/_components/cart:ItemForm/action/1'));
        $middleware->handle(new Envelope(new NotificationCommand('Same notification')), $stack);
        $requestStack->pop();

        $requestStack->push(Request::create('/_components/cart:ItemForm/action/2'));
        $middleware->handle(new Envelope(new NotificationCommand('Same notification')), $stack);
        $requestStack->pop();
    }
}
