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

use CpCreation\VitiCore\Bridge\Doctrine\EventSubscriber\CartItemSkuSnapshotSubscriber;
use CpCreation\VitiCore\Cart\Model\CartItem;
use CpCreation\VitiCore\Product\Model\Product;
use CpCreation\VitiCore\Product\Model\ProductType;
use CpCreation\VitiCore\Product\Model\ProductVariant;
use CpCreation\VitiCore\Product\ProductVariantSkuResolver;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Doctrine\Persistence\ObjectManager;
use PHPUnit\Framework\TestCase;

final class CartItemSkuSnapshotSubscriberTest extends TestCase
{
    public function testCapturesTheEffectiveSkuOnlyOnce(): void
    {
        $product = new Product();
        $product->setSku('BRUT-RESERVE');
        $type = new ProductType();
        $type->setCode('BOUTEILLE');
        $variant = new ProductVariant();
        $variant->setProduct($product);
        $variant->setType($type);
        $item = new CartItem();
        $item->setVariant($variant);
        $event = new LifecycleEventArgs($item, $this->createStub(ObjectManager::class));
        $subscriber = new CartItemSkuSnapshotSubscriber(new ProductVariantSkuResolver());

        $subscriber->prePersist($event);
        self::assertSame('BRUT-RESERVE-BOUTEILLE', $item->getSkuSnapshot());

        $product->setSku('NOUVELLE-REFERENCE');
        $subscriber->prePersist($event);
        self::assertSame('BRUT-RESERVE-BOUTEILLE', $item->getSkuSnapshot());
    }
}
