<?php
namespace Misuzu\Console\Commands;

use InvalidArgumentException;
use Index\Data\Migration\FsDbMigrationRepo;
use Misuzu\MisuzuContext;
use Misuzu\Console\CommandArgs;
use Misuzu\Console\CommandInterface;

class NewMigrationCommand implements CommandInterface {
    private MisuzuContext $context;

    public function __construct(MisuzuContext $ctx) {
        $this->context = $ctx;
    }

    public function getName(): string {
        return 'new-mig';
    }
    public function getSummary(): string {
        return 'Creates a new database migration.';
    }

    public function dispatch(CommandArgs $args): void {
        $repo = $this->context->createMigrationRepo();
        if(!($repo instanceof FsDbMigrationRepo)) {
            echo 'Migration repository type does not support creation of templates.' . PHP_EOL;
            return;
        }

        $baseName = implode(' ', $args->getArgs());
        $manager = $this->context->createMigrationManager();

        try {
            $names = $manager->createNames($baseName);
        } catch(InvalidArgumentException $ex) {
            echo $ex->getMessage() . PHP_EOL;
            return;
        }

        $repo->saveMigrationTemplate($names->name, $manager->template($names->className));

        echo "Template for '{$names->className}' has been saved to {$names->name}.php." . PHP_EOL;
    }
}
