<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Automation\Trigger\InvocationMatcher;


use idoit\Module\SyneticsFlows\Automation\Trigger\ConditionMatcher\ConditionMatcher;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\Invocation;

class CollectionMatcher implements InvocationMatcher
{
    public function __construct(private iterable $matchers, private ConditionMatcher $conditionMatcher)
    {
    }

    public function findAutomations(Invocation $invocation): iterable
    {
        foreach ($this->matchers as $matcher) {
            if (!$matcher instanceof InvocationMatcher || !$matcher->supports($invocation)) {
                continue;
            }
            foreach ($matcher->findAutomations($invocation) as $automation) {
                $condition = $automation->getCondition();
                if ($condition && $this->conditionMatcher->supports($condition, $invocation) &&  $this->conditionMatcher->isMatched($condition, $invocation)) {
                    yield $automation;
                }
            }
        }
    }

    public function supports(Invocation $invocation): bool
    {
        foreach ($this->matchers as $matcher) {
            if ($matcher instanceof InvocationMatcher && $matcher->supports($invocation)) {
                return true;
            }
        }
        return false;
    }
}