<?php

declare(strict_types=1);

namespace Fennec\Console\Command;

use Fennec\Console\CommandInterface;
use Fennec\Console\ConsoleOutput;
use Fennec\Console\Input;

/**
 * Génère le squelette d'une nouvelle commande applicative, sans jamais toucher au noyau.
 */
final class MakeCommandCommand implements CommandInterface
{
    public function __construct(
        private readonly ConsoleOutput $output,
        private readonly string $commandDirectory,
        private readonly string $commandNamespace,
    ) {
    }

    public function getName(): string
    {
        return 'make:command';
    }

    public function getDescription(): string
    {
        return 'Génère le squelette d\'une nouvelle commande applicative.';
    }

    public function execute(array $arguments): int
    {
        $input = new Input($arguments);
        $name = $input->getArgument(0);

        if ($name === null) {
            $this->output->error('Usage: make:command <NomDeLaCommande>');

            return 1;
        }

        $className = \str_ends_with($name, 'Command') ? $name : $name . 'Command';
        $filePath = $this->commandDirectory . \DIRECTORY_SEPARATOR . $className . '.php';

        if (\is_file($filePath)) {
            $this->output->error(\sprintf('Le fichier "%s" existe déjà.', $filePath));

            return 1;
        }

        if (!\is_dir($this->commandDirectory) && !\mkdir($this->commandDirectory, recursive: true) && !\is_dir($this->commandDirectory)) {
            $this->output->error(\sprintf('Impossible de créer le répertoire "%s".', $this->commandDirectory));

            return 1;
        }

        \file_put_contents($filePath, $this->buildSkeleton($className));
        $this->output->success(\sprintf('Commande créée : %s', $filePath));

        return 0;
    }

    private function buildSkeleton(string $className): string
    {
        return <<<PHP
        <?php

        declare(strict_types=1);

        namespace {$this->commandNamespace};

        use Fennec\Console\CommandInterface;

        final class {$className} implements CommandInterface
        {
            public function getName(): string
            {
                return 'app:command-name';
            }

            public function getDescription(): string
            {
                return 'Description de la commande.';
            }

            public function execute(array \$arguments): int
            {
                // TODO: implémenter la commande

                return 0;
            }
        }

        PHP;
    }
}
