<?php

declare(strict_types=1);

namespace Dedi\SyliusTheme\Twig;

use Doctrine\Common\Collections\Collection;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Component\Inventory\Checker\AvailabilityCheckerInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class AvailableVariantFilterExtension extends AbstractExtension
{
    private AvailabilityCheckerInterface $checker;

    public function __construct(AvailabilityCheckerInterface $checker)
    {
        $this->checker = $checker;
    }

    public function getFilters(): array
    {
        return [
            new TwigFilter('filter_available_variants', [$this, 'filterAvailableVariants']),
        ];
    }

    public function filterAvailableVariants(Collection $collection): Collection
    {
        $clonedCollection = clone $collection;

        /** @var ProductVariantInterface $variant */
        foreach ($clonedCollection as $variant) {
            if (!$this->checker->isStockAvailable($variant)) {
                $clonedCollection->removeElement($variant);
            }
        }

        return $clonedCollection;
    }
}
