<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Automation\Action\ExecutionFactory;

use idoit\Module\SyneticsFlows\Automation\Action\ActionType\ActionType;
use idoit\Module\SyneticsFlows\Automation\Automation;
use idoit\Module\SyneticsFlows\Automation\Action\ExecutionInfo\ExecutionInfo;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\Invocation;

class CollectionExecutionFactory implements ExecutionFactory
{
    /**
     * @param iterable<ExecutionFactory> $factories
     */
    public function __construct(private iterable $factories)
    {
    }

    public function createExecution(Invocation $invocation, Automation $automation, ActionType $actionType): ?ExecutionInfo
    {
        foreach ($this->factories as $factory) {
            if ($factory->supports($actionType)) {
                $result = $factory->createExecution($invocation, $automation, $actionType);
                if ($result instanceof ExecutionInfo) {
                    return $result;
                }
            }
        }

        return null;
    }

    public function supports(ActionType $actionType): bool
    {
        foreach ($this->factories as $factory) {
            if ($factory->supports($actionType)) {
                return true;
            }
        }

        return false;
    }
}