<?php declare(strict_types = 1);

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

use idoit\Module\SyneticsFlows\Automation\TriggerFacade;
use idoit\Module\SyneticsFlows\Validation\Required;
use idoit\Module\SyneticsFlows\Validation\ValidationCallback;
use idoit\Module\SyneticsFlows\Validation\ValidationMessage;

class CallIdoitCommandAction extends ActionType
{
    public function __construct(
        #[Required]
        private ?string $command = null,
        private ?array $parameters = null,
    )
    {
    }

    public function getCommand(): ?string
    {
        return $this->command;
    }

    public function getParameters(): ?array
    {
        return $this->parameters;
    }

    #[ValidationCallback]
    public function validate(array $path): array
    {
        $results = [];
        if (!$this->command) {
            return $results;
        }
        $config = TriggerFacade::getIdoitCommandConfiguration()->get($this->command);
        if (!$config) {
            return $results;
        }
        $errors =  $config->validate($this);

        foreach ($errors as $error) {
            if (!$error instanceof ValidationMessage) {
                continue;
            }
            $results[] = new ValidationMessage([...$path, ...$error->getPath()], $error->getMessage());
        }

        return $results;
    }
}
