<?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\Factory\Abilities\OverloadableFactory;
use CouponsPlus\App\Coupon\Tree\Finders\Sets\OffersDataSet;
use CouponsPlus\App\Coupon\Tree\Cart\CartModifiedException;
use CouponsPlus\App\Coupon\Tree\Abilities\FindableOffersFromBranch;
use CouponsPlus\App\Coupon\Tree\OfferItemsSetFilters\OffersItemsSetResolverFromData;

class LeavesBranchRuntimeOffersFinder implements FindableOffersFromBranch, OverloadableFactory
{
    protected OffersItemsSetResolverFromData $offersItemsSetResolverFromData;

    public function __construct(OffersItemsSetResolverFromData $offersItemsSetResolverFromData)
    {
        $this->offersItemsSetResolverFromData = $offersItemsSetResolverFromData;
    }

    /** @param Branch $value */
    public function canCreate( $value): bool
    {
        return $value->getType()->is('offers');            
    }

    /**
     * todo: so currently we are creating a runtime offers instance from the data and then destroying that one (auto by the garbage collector) and we are re-creating the instance later in the system. why not just preserve that instance and use it later? The offersItemsSetResolverFromData is the one creating the runtime instance.
     * @throws CartModifiedException
     */
    public function findOffers(ItemsSet $itemsSet, Branch $branch): CartComponentsSet
    {
        (object) $offersDataSet = new OffersDataSet($branch->getChildren()->first());

        $this->offersItemsSetResolverFromData->setOfferData($branch->getChildren()->first());

        $offersDataSet->setOfferItems(
            $this->offersItemsSetResolverFromData->resolveItemsToUse($itemsSet)
        );

        return $offersDataSet;
    } 
}