<?php

namespace idoit\Module\SyneticsJdisc\ApiEndpoint;

use Exception;
use idoit\Api\EndpointDefinition;
use idoit\Api\EndpointInterface;
use idoit\Api\JsonRpcResponse;
use idoit\Api\Parameter\OptionalParameter;
use idoit\Api\Parameter\Parameter;
use idoit\Component\FeatureManager\FeatureManager;
use idoit\Module\Api\ApiCommandRunner;
use idoit\Module\Api\Exception\JsonRpc\InternalErrorException;
use idoit\Module\Synetics_jdisc\Console\Command\JDiscDiscoveryCommand;
use isys_application;
use Symfony\Component\HttpFoundation\Request;
use Throwable;

class DiscoveryCommand implements EndpointInterface
{
    public function getDefinition(): EndpointDefinition
    {
        return new EndpointDefinition(
            'console.import.jdiscdiscovery',
            'Triggers a JDisc discovery (API Access to the JDisc server is defined in the GUI)',
            [
                new OptionalParameter('options', Parameter::TYPE_ARRAY, 'Command options, as an associative array'),
                new OptionalParameter('arguments', Parameter::TYPE_ARRAY, 'Command arguments, as an associative array')
            ]
        );
    }

    public function request(Request $request): JsonRpcResponse
    {
        // Check if command exists.
        if (!class_exists(JDiscDiscoveryCommand::class)) {
            throw new InternalErrorException('Unable to find desired command.');
        }

        // Check if feature is active.
        if (class_exists(FeatureManager::class) && !FeatureManager::isFeatureActive('jdisc-import')) {
            throw new Exception('Command disabled, please check the feature management.');
        }

        $parameters = $request->request->all();

        try {
            // Create command runner (copied from 'isys_api_model_console').
            $commandRunner = new ApiCommandRunner(isys_application::instance()->app_path, JDiscDiscoveryCommand::NAME);

            foreach ($parameters['options'] ?? [] as $name => $value) {
                $commandRunner->addOption($name, $value);
            }

            foreach ($parameters['arguments'] ?? [] as $name => $value) {
                $commandRunner->addArgument($name, $value);
            }

            // Run command
            $commandRunner->run();

            return new JsonRpcResponse([
                'success' => $commandRunner->success(),
                'output'  => $commandRunner->getCommandOutput()
            ]);
        } catch (Throwable $e) {
            return new JsonRpcResponse([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    }
}
