<?php

/*
 * 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\LegacyOrderImport;

use CpCreation\VitiCore\Cart\CartPricing;
use CpCreation\VitiCore\Cart\CartPromos;
use CpCreation\VitiCore\Cart\CartShipping;
use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Cart\Model\CartCheckout;
use CpCreation\VitiCore\Cart\Model\CartItem;
use PHPUnit\Framework\TestCase;

final class LegacyOrderCartSnapshotTest extends TestCase
{
    public function testLegacyImportFreezesAnUnpaidCartCommerceSnapshot(): void
    {
        $cart = new Cart();
        $pricing = $this->pricing(4200);
        $shipping = new CartShipping(1200, 0.2, 'Transport historique');
        $promos = new CartPromos();

        $cart->setPricing($pricing);
        $cart->setCartShipping($shipping);
        $cart->setCartPromos($promos);

        $checkout = new CartCheckout();
        $checkout->setResponse([
            'legacy_order_import' => ['source' => 'viti-core-master'],
        ]);
        $cart->setCartCheckout($checkout);

        self::assertFalse($cart->isCheckoutPayed());
        self::assertTrue($cart->isLegacyOrderImport());
        self::assertTrue($cart->hasFrozenCommerceSnapshot());

        $cart->setPricing($this->pricing(9999));
        $cart->setCartShipping(null);
        $cart->setCartPromos(null);

        self::assertSame($pricing, $cart->getPricing());
        self::assertSame($shipping, $cart->getCartShipping());
        self::assertSame($promos, $cart->getCartPromos());
    }

    public function testUnrelatedCheckoutResponseDoesNotFreezeAnUnpaidCart(): void
    {
        $cart = new Cart();
        $checkout = new CartCheckout();
        $checkout->setResponse(['status' => 'pending']);
        $cart->setCartCheckout($checkout);

        self::assertFalse($cart->isLegacyOrderImport());
        self::assertFalse($cart->hasFrozenCommerceSnapshot());
    }

    public function testDetachedHistoricalLineDoesNotBreakQuantityStatistics(): void
    {
        $cart = new Cart();
        $item = new CartItem();
        $item->setQuantity(3);
        $cart->addItem($item);

        self::assertNull($item->getVariant());
        self::assertSame(0.0, $cart->getQuantityAllAbsolute());
    }

    private function pricing(int $totalTTC): CartPricing
    {
        return new CartPricing(
            lines: [],
            taxRate: 0.2,
            subtotalHT: $totalTTC,
            subtotalTax: 0,
            subtotalTTC: $totalTTC,
            discountHT: 0,
            discountTax: 0,
            discountTTC: 0,
            degressiveHT: 0,
            degressiveTax: 0,
            degressiveTTC: 0,
            totalHT: $totalTTC,
            totalTax: 0,
            totalTTC: $totalTTC,
        );
    }
}
