<?php
// CoreFlux/core/CLI/Commands/MakeMigrationCommand.php

namespace Core\CLI\Commands;

use Core\CLI\Command;

class MakeMigrationCommand implements Command
{
    public function getName(): string
    {
        return 'make:migration';
    }

    public function getDescription(): string
    {
        return 'Creates a new migration file.';
    }

    public function execute(array $args): int
    {
        $migrationName = $args[0] ?? null;

        if (!$migrationName) {
            echo "Error: Please provide a migration name. Usage: php bin/coreflux make:migration create_users_table\n";
            return 1;
        }

        $timestamp = date('YmdHis');
        $fileName = "{$timestamp}_{$migrationName}.php";

        // Assuming FS_STORAGE_PATH is defined (e.g., in bin/coreflux)
        $migrationsDir = FS_STORAGE_PATH . DIRECTORY_SEPARATOR . 'migrations';

        if (!is_dir($migrationsDir)) {
            if (!mkdir($migrationsDir, 0775, true)) {
                echo "Error: Failed to create migrations directory: {$migrationsDir}. Check permissions.\n";
                return 1;
            }
            echo "Info: Created migrations directory: {$migrationsDir}\n";
        }

        $filePath = $migrationsDir . DIRECTORY_SEPARATOR . $fileName;

        if (file_exists($filePath)) {
            echo "Error: Migration file '{$fileName}' already exists.\n";
            return 1;
        }

        $content = $this->getMigrationFileContent($migrationName);

        if (file_put_contents($filePath, $content) !== false) {
            echo "Success: Migration '{$fileName}' created at '{$filePath}'.\n";
            return 0;
        } else {
            echo "Error: Failed to create migration file. Check permissions for '{$migrationsDir}'.\n";
            return 1;
        }
    }

    private function getMigrationFileContent(string $migrationName): string
    {
        // Simple pluralization for table names
        $tableName = $migrationName;
        if (str_starts_with($migrationName, 'create_')) {
            $tableName = str_replace('create_', '', $migrationName);
            if (!str_ends_with($tableName, 's')) {
                $tableName .= 's';
            }
        }
        
        return <<<PHP
<?php

use Core\\Database\\Schema;
use Core\\Database\\MigrationOperation;

return new class implements MigrationOperation {
    public function up()
    {
        // Example for creating a table:
        // Schema::createTable('{$tableName}', [
        //     'id' => 'INT PRIMARY KEY AUTO_INCREMENT',
        //     'name' => 'VARCHAR(255) NOT NULL',
        //     'created_at' => 'DATETIME DEFAULT CURRENT_TIMESTAMP'
        // ]);
        
        // TODO: define your 'up' migration for {$migrationName}
    }

    public function down()
    {
        // Example for dropping a table:
        // Schema::dropTable('{$tableName}');

        // TODO: define your 'down' migration for {$migrationName}
    }
};
PHP;
    }
}