<?php
namespace Core\CLI\Commands;

use Core\CLI\Command;

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

    public function getDescription(): string
    {
        return 'Creates a new test file with boilerplate in the test folder.';
    }

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

        if (!$testName) {
            echo "Error: Please provide a test file name. Usage: php bin/coreflux make:test MyTest.php\n";
            return 1;
        }

        // Ensure it ends with .php
        if (!str_ends_with($testName, '.php')) {
            $testName .= '.php';
        }

        $testPath = ROOT_PATH . DIRECTORY_SEPARATOR . 'tests' . DIRECTORY_SEPARATOR . $testName;

        if (file_exists($testPath)) {
            echo "Error: Test file already exists at '$testPath'.\n";
            return 1;
        }

        // Calculate depth from the test file to project root
        $testDir = dirname($testPath);
        $rootDir = ROOT_PATH;
        $relativePathParts = array_diff(explode(DIRECTORY_SEPARATOR, $testDir), explode(DIRECTORY_SEPARATOR, $rootDir));
        $levelsUp = count($relativePathParts);

        // Construct the correct relative path to vendor/autoload.php
        $vendorPath = str_repeat('../', $levelsUp) . 'vendor/autoload.php';

        // Construct the correct relative path for ROOT_PATH
        $rootPathDefine = str_repeat('../', $levelsUp); // Always points to project root

        // Boilerplate content
        $content = <<<PHP
<?php
require __DIR__ . '/$vendorPath';

define('ROOT_PATH', realpath(__DIR__ . '/$rootPathDefine'));
define('APP_PATH', ROOT_PATH . DIRECTORY_SEPARATOR . 'app');
define('CORE_PATH', ROOT_PATH . DIRECTORY_SEPARATOR . 'core');
define('VENDOR_PATH', ROOT_PATH . DIRECTORY_SEPARATOR . 'vendor');
define('CONFIG_PATH', APP_PATH . DIRECTORY_SEPARATOR . 'config');
define('STORAGE_PATH', ROOT_PATH . DIRECTORY_SEPARATOR . 'storage');

// Your test code goes here

PHP;

        // Make sure the directory exists
        if (!is_dir($testDir)) {
            mkdir($testDir, 0777, true);
        }

        if (file_put_contents($testPath, $content) === false) {
            echo "Error: Could not create test file at '$testPath'. Check permissions.\n";
            return 1;
        }

        echo "Success: Test file created at '$testPath'.\n";
        return 0;
    }
}
