<?php declare(strict_types = 1);

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

use idoit\Module\SyneticsFlows\Automation\Action\ExecutionResult\ErrorExecutionResult;
use idoit\Module\SyneticsFlows\Automation\Action\ExecutionResult\ExecutionResult;
use idoit\Module\SyneticsFlows\Automation\Execution;
use Throwable;

class CollectionExecution implements PerformExecution
{
    public function __construct(private iterable $executions)
    {
    }

    public function perform(Execution $execution): ExecutionResult
    {
        try {
            foreach ($this->executions as $runner) {
                if ($runner instanceof PerformExecution && $runner->supports($execution)) {
                    return $runner->perform($execution);
                }
            }
        } catch (Throwable $exception) {
            return new ErrorExecutionResult($exception->getMessage());
        }

        return new ErrorExecutionResult('Not supported execution');
    }

    public function supports(Execution $execution): bool
    {
        foreach ($this->executions as $runner) {
            if ($runner instanceof PerformExecution && $runner->supports($execution)) {
                return true;
            }
        }
        return false;
    }
}