<?php

namespace CouponsPlus\App\Coupon\Tree;

use CouponsPlus\App\Conditions\Abilities\TestableComposite;
use CouponsPlus\App\Conditions\ItemsSet;
use CouponsPlus\App\Coupon\Tree\Abilities\FilterableGroup;
use CouponsPlus\Original\Collections\Collection;
use CouponsPlus\App\Coupon\Tree\Sets\FromTestableCompositeWithCollectionItemsSetSource;

class ANDTestableGroup implements FilterableGroup
{
    public bool $canRecordSource = true;

    public function filter(Collection $testableGroups, ItemsSet $passedItems): ItemsSet
    {
        (object) $filteredItems = new ItemsSet([]);

        /**
         * This next line is a literal duplicate of ORInclusiveTestableGroup. we need to refactor this somehow
         */
        if ($this->canRecordSource) {
            $filteredItems->setSource(
                new FromTestableCompositeWithCollectionItemsSetSource(
                    new TestableGroup(new static)
                )
            );
        }

        /** @var TestableComposite $testableGroup */
        foreach ($testableGroups->asArray() as $testableGroup) {
            $filteredItemsForThisGroup = $testableGroup->filterSet($passedItems);

            if ($filteredItemsForThisGroup->getItems()->haveNone()) {
                return new ItemsSet([]);
            }

            $filteredItems->addItems($filteredItemsForThisGroup, $testableGroup);
        }

        return $filteredItems;
    } 
}