<?php

namespace CouponsPlus\App\Coupon\Tree\Factories;

use CouponsPlus\App\Coupon\Tree\Abilities\FilterableGroup;
use CouponsPlus\App\Coupon\Tree\Abilities\TestableGroupData;

class CachedFilterableGroupFactory implements FilterableGroupFactoryInterface
{
    private $instances = [];
    private $decoratedFactory;

    public function __construct(FilterableGroupFactoryInterface $decoratedFactory)
    {
        $this->decoratedFactory = $decoratedFactory;
    }

    public function create(string $type, $testableGroupData): FilterableGroup
    {
        // Return cached instance if available
        if (isset($this->instances[$type])) {
            return $this->instances[$type];
        }

        // Delegate to decorated factory and cache the result
        $instance = $this->decoratedFactory->create($type);
        $this->instances[$type] = $instance;
        
        return $instance;
    }
}
