<?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\JDiscImportCommand;
use isys_application;
use Symfony\Component\HttpFoundation\Request;
use Throwable;

class ImportCommand implements EndpointInterface
{
    public function getDefinition(): EndpointDefinition
    {
        return new EndpointDefinition(
            'console.import.jdisc',
            'Imports data from a JDisc server (SQL server access 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(JDiscImportCommand::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, JDiscImportCommand::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()
            ]);
        }
    }
}
