<?php

namespace CouponsPlus\App\Coupon\Tree\Finders;

use CouponsPlus\App\Conditions\ItemsSet;
use CouponsPlus\App\Coupon\CartComponentsSet;
use CouponsPlus\App\Coupon\Tree\Abilities\Branch;
use CouponsPlus\App\Coupon\Tree\Abilities\FindableOffersFromBranch;
use CouponsPlus\App\Coupon\Tree\Abilities\Node;
use CouponsPlus\App\Offers\OffersSet;
use CouponsPlus\App\Offers\OffersSetCollection;

/**
 * Multi branch was decided against in favor of groves (multiple trees)
 * and there fore this is currently not being used and has not been tested.
 */
class MultiBranchRuntimeOffersFinder implements FindableOffersFromBranch
{
    public function __construct(
        protected RuntimeNodeOffersFinder $runtimeNodeOffersFinder
    ) {}
    
    public function findOffers(ItemsSet $itemsSet, Branch $branch): CartComponentsSet
    {
        (object) $offersSetCollection = new OffersSetCollection([]);

        $branch->getChildren()->forEvery(function(Node $node) use ($offersSetCollection, $itemsSet) : void {
            /** @var OffersSetCollection */
            (object) $offersSetCollection = $this->runtimeNodeOffersFinder->findOffers($itemsSet, $node);

            $offersSetCollection->getItems()->forEvery(function(OffersSet $offersSet) use ($offersSetCollection) : void {
                $offersSetCollection->addOffersSet($offersSet);     
            });
        });

        return $offersSetCollection;
    } 
}