<?php declare(strict_types = 1);

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

use idoit\Module\SyneticsFlows\Automation\Trigger\Condition\Condition;
use idoit\Module\SyneticsFlows\Automation\Trigger\Condition\OrCondition;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\Invocation;

class OrConditionMatcher implements ConditionMatcher
{
    /**
     * @param ArrayConditionMatcher $matcher
     */
    public function __construct(private ArrayConditionMatcher $matcher)
    {
    }

    /**
     * @param Condition $condition
     *
     * @return bool
     */
    public function isMatched(Condition $condition, Invocation $invocation): bool
    {
        if (!$condition instanceof OrCondition) {
            return false;
        }

        $isMatched = true;

        foreach ($condition->getItems() as $conditionItem) {
            if (!$this->matcher->supports($conditionItem, $invocation)) {
                continue;
            }
            if ($this->matcher->isMatched($conditionItem, $invocation)) {
                return true;
            }
            $isMatched = false;
        }

        return $isMatched;
    }

    /**
     * @param Condition $condition
     *
     * @return bool
     */
    public function supports(Condition $condition, Invocation $invocation): bool
    {
        return $condition instanceof OrCondition;
    }
}