<?php

namespace idoit\Module\SyneticsFlows\Controller;

use idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\IdoitCommandConfiguration;
use idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\Option\ValueProviderOption;
use idoit\Module\SyneticsFlows\Automation\TriggerFacade;
use idoit\Module\SyneticsFlows\Controller\Response\NotFoundResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class CliController
{
    /**
     * @var IdoitCommandConfiguration|null
     */
    private ?IdoitCommandConfiguration $configuration = null;

    /**
     * @return IdoitCommandConfiguration
     * @throws \Exception
     */
    public function getService(): IdoitCommandConfiguration
    {
        if (!$this->configuration) {
            $this->configuration = TriggerFacade::getIdoitCommandConfiguration();
        }
        return $this->configuration;
    }

    /**
     * @param string $command
     * @param string $id
     *
     * @return JsonResponse
     */
    public function getValues(string $command, string $id, Request $request): JsonResponse
    {
        $dependencies = [];
        $passedDependencies = $request->get('dependencies');
        if (is_string($passedDependencies)) {
            $parameters = json_decode($passedDependencies, true);
            if (is_array($parameters)) {
                $dependencies = $parameters;
            }
        }
        $config = $this->getService()->get($command);
        if (!$config) {
            return new NotFoundResponse('Command');
        }

        foreach ($config->getOptions() as $option) {
            if ($option instanceof ValueProviderOption && $option->getName() === $id) {
                return new JsonResponse($option->getValues($dependencies));
            }
        }
        return new NotFoundResponse('Option');
    }
}
