<?php declare(strict_types = 1);

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

use idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\DataSource\DataSource;
use idoit\Module\SyneticsFlows\Serialization\Exclude;
use idoit\Module\SyneticsFlows\Validation\OneOf;
use idoit\Module\SyneticsFlows\Validation\Required;
use idoit\Module\SyneticsFlows\Validation\ValidationMessage;

class DynamicStringSelectOption extends IdoitCliOption implements ValueProviderOption
{
    /**
     * @param string $name
     * @param string $description
     * @param bool $required
     * @param DataSource $dataSource
     * @param string|null $defaultValue
     * @param array $dependencies
     */
    public function __construct(
        string $name,
        string $description,
        bool $required,
        #[Exclude]
        private DataSource $dataSource,
        private ?string $defaultValue,
        array $dependencies = []
    )
    {
        parent::__construct($name, $description, $required, $dependencies);
    }

    public function validate(mixed $value, array $parameters): array
    {
        $errors = parent::validate($value, $parameters);

        if (!$value) {
            return $errors;
        }

        $sourceValues = array_map(
            fn(SelectOptionValue $optionValue) => $optionValue->getValue(),
            $this->getValues($parameters)
        );

        if (!in_array($value, $sourceValues)) {
            $errors[] = new ValidationMessage([$this->name], 'Invalid value ' . $value . '.');
        }

        return $errors;
    }

    public function getValues(array $parameters): array
    {
        return $this->dataSource->getValues($parameters);
    }

    public function getDefaultValue(): ?string
    {
        return $this->defaultValue;
    }
}