<?php

declare(strict_types=1);

namespace KupShop\KupShopBundle\PriceType;

use KupShop\CatalogBundle\ProductList\ProductCollection;
use KupShop\ContentBundle\Entity\ProductUnified;
use KupShop\KupShopBundle\Util\Price\Price;

class PriceListPriceType extends AbstractPriceType
{
    public function __construct(public int $priceListId)
    {
    }

    public function getPrice(ProductUnified $product): ?Price
    {
        $pricelist_product = $product->getPricelists()[$this->priceListId] ?? null;
        if (!$pricelist_product) {
            return null;
        }

        if ($id_variation = $product->getVariationId()) {
            $pricelist_product = $pricelist_product['variations'][$id_variation] ?? $pricelist_product;
        }

        return $pricelist_product['productPrice'] ?? null;
    }

    public function prefetchProductCollection(ProductCollection $collection)
    {
        $first = $collection->first();
        if ($first && !isset($first->pricelists)) {
            $collection->fetchPricelists(false);
        }
    }
}
