<?php

namespace idoit\Module\Synetics_jdisc\Console\Command;

use Axtiva\FlexibleGraphql\Builder\Foundation\CodeGeneratorBuilder;
use Axtiva\FlexibleGraphql\Generator\Config\Foundation\Psr4\CodeGeneratorConfig;
use Axtiva\FlexibleGraphql\Utils\SchemaBuilder;
use idoit\Console\Command\AbstractCommand;
use isys_module_synetics_jdisc;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class JDiscGraphqlSchemaBuilderCommand extends AbstractCommand
{
    const NAME = 'internal:jdisc-graphql-builder';

    const HIDE_COMMAND = true;

    /**
     * Get description for command
     *
     * @return string
     */
    public function getCommandDescription()
    {
        return 'Creates the GraphQL Schema.';
    }

    /**
     * Get name for command
     *
     * @return string
     */
    public function getCommandName()
    {
        return self::NAME;
    }

    /**
     * @return InputDefinition
     */
    public function getCommandDefinition()
    {
        $jdiscPath = isys_module_synetics_jdisc::getPath();
        $file = $jdiscPath . '/src/Graphql/GraphQL_Schema.txt';

        return new InputDefinition([
            new InputOption('file', null, InputOption::VALUE_REQUIRED, 'The file where the schema is located', $file),
        ]);
    }

    /**
     * @return bool
     */
    public function isConfigurable()
    {
        return true;
    }

    /**
     * @return string[]
     */
    public function getCommandUsages()
    {
        return [];
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return int
     * @throws \Axtiva\FlexibleGraphql\Exception\SchemaParserException
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $exitCode = Command::SUCCESS;
        $file = $input->getOption('file');

        if (!file_exists($file)) {
            $output->writeln("File {$file} not found");
            return Command::FAILURE;
        }
        $schema = SchemaBuilder::build($file);

        $namespace = 'idoit\Module\SyneticsJdisc\Graphql\Schema';
        $schemaPath = isys_module_synetics_jdisc::getPath() . 'src/Graphql/Schema';

        $builder = new CodeGeneratorBuilder(new CodeGeneratorConfig($schemaPath, CodeGeneratorConfig::V7_4, $namespace));

        $generator = $builder->build();

        foreach ($generator->generateAllTypes($schema) as $filename);

        return $exitCode;
    }
}
