<?php

declare(strict_types=1);

/*
 * This file is part of the Serenity 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\Product;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Context\GroupContext;
use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Cart\Model\CartItem;
use CpCreation\VitiCore\Product\DTO\DegressiveContext;
use CpCreation\VitiCore\Product\Repository\ProductPriceGroupRepository;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

final class DegressiveContextFactory
{
    public function __construct(
        private RequestStack $requestStack,
        private ProductPriceGroupRepository $productPriceGroupRepository,
    ) {
    }

    public function createFromCart(Cart $cart): ?DegressiveContext
    {
        $priceGroupId = GroupContext::$groupId;

        if (!\is_string($priceGroupId) || '' === $priceGroupId) {
            $priceGroupId = $this->getSession()?->get('groupPrice');
        }

        if (!\is_string($priceGroupId) || '' === $priceGroupId) {
            $priceGroupId = $this->productPriceGroupRepository->getGroupByDefault()?->getId()?->toString();
        }

        if (!\is_string($priceGroupId) || '' === $priceGroupId) {
            return null;
        }

        $equivalencyQty = 0.0;

        /** @var CartItem $item */
        foreach ($cart->getItems() as $item) {
            $equivalencyQty += $item->getQuantity() * ($item->getVariant()->getType()->getEquivalencyDegressive() ?? 0);
        }

        if ($equivalencyQty <= 0) {
            return null;
        }

        return new DegressiveContext(
            cart: $cart,
            priceGroupId: $priceGroupId,
            equivalencyQty: $equivalencyQty,
        );
    }

    private function getSession(): ?SessionInterface
    {
        return $this->requestStack->getSession();
    }
}
