<?php declare(strict_types = 1);

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

use idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\Option\IdoitCliOption;

class OptionsOrderConverter implements OrderConverter
{
    /**
     * @param array $optionsOrder
     */
    public function __construct(private array $optionsOrder)
    {
    }

    /**
     * @param string $commandName
     * @param array $options
     * @return array
     */
    public function convert(string $commandName, array $options): array
    {
        if (!$this->supports($commandName) || !count($options)) {
            return $options;
        }

        $orderLookup = array_flip($this->optionsOrder[$commandName]);

        usort($options, function (IdoitCliOption $a, IdoitCliOption $b) use ($orderLookup) {
            return ($orderLookup[$a->getName()] ?? PHP_INT_MAX) <=> ($orderLookup[$b->getName()] ?? PHP_INT_MAX);
        });

        return $options;
    }

    /**
     * @param string $commandName
     * @return bool
     */
    public function supports(string $commandName): bool
    {
        return isset($this->optionsOrder[$commandName]);
    }
}