<?php

declare(strict_types=1);

namespace Drush\Attributes;

use Attribute;
use Consolidation\AnnotatedCommand\CommandData;
use Consolidation\AnnotatedCommand\CommandError;
use Drush\Utils\StringUtils;

#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_CLASS)]
class ValidateConfigName extends ValidatorBase implements ValidatorInterface
{
    /**
     * @param string $argumentName
     *   The name of the argument which specifies the config ID.
     */
    public function __construct(
        public string $argumentName = 'config_name'
    ) {
    }

    public function validate(CommandData $commandData)
    {
        $configName = $commandData->input()->getArgument($this->argumentName);
        $names = StringUtils::csvToArray($configName);
        foreach ($names as $name) {
            $config = \Drupal::config($name);
            if ($config->isNew()) {
                $msg = dt('Config !name does not exist', ['!name' => $name]);
                return new CommandError($msg);
            }
        }
    }
}
