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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Context\GroupContext;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\EventListener\GroupContextListener;
use CpCreation\VitiCore\Product\Model\ProductPriceGroup;
use CpCreation\VitiCore\Product\Repository\ProductPriceCodeRepository;
use CpCreation\VitiCore\Product\Repository\ProductPriceGroupRepository;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelInterface;

final class GroupContextListenerTest extends TestCase
{
    protected function tearDown(): void
    {
        GroupContext::$groupId = null;
        GroupContext::$partnerCode = null;
    }

    public function testStatelessRequestUsesDefaultGroupWithoutStartingSession(): void
    {
        $defaultGroup = new ProductPriceGroup();
        $groupRepository = $this->createMock(ProductPriceGroupRepository::class);
        $groupRepository->expects(self::once())
            ->method('getGroupByDefault')
            ->willReturn($defaultGroup);
        $priceCodeRepository = $this->createMock(ProductPriceCodeRepository::class);
        $priceCodeRepository->expects(self::never())->method('find');

        $request = Request::create('/api/commerce/v1/products');
        $request->attributes->set('_stateless', true);
        $session = new Session(new MockArraySessionStorage());
        $request->setSession($session);

        $listener = new GroupContextListener(
            $this->createStub(Security::class),
            $groupRepository,
            $priceCodeRepository,
        );
        $listener(new RequestEvent(
            $this->createStub(KernelInterface::class),
            $request,
            HttpKernelInterface::MAIN_REQUEST,
        ));

        self::assertFalse($session->isStarted());
        self::assertSame($defaultGroup->getId()->toString(), GroupContext::$groupId);
        self::assertNull(GroupContext::$partnerCode);
    }
}
