<?php
namespace Core\CLI\Commands;

use Core\CLI\Command;

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

    public function getDescription(): string
    {
        return 'Runs a PHP test file or directory.';
    }

    /**
     * Execute the test command
     *
     * Usage examples:
     * php bin/coreflux run:test core/Database/test.php
     * php bin/coreflux run:test core/Database/Tests/
     */
    public function execute(array $args): int
    {
        $fileOrDir = $args[0] ?? null;

        if (!$fileOrDir) {
            echo "Error: Please provide a test file or directory to run.\n";
            echo "Usage: php bin/coreflux run:test path/to/test.php\n";
            return 1;
        }

        if (!file_exists($fileOrDir)) {
            echo "Error: File or directory '{$fileOrDir}' does not exist.\n";
            return 1;
        }

        if (is_dir($fileOrDir)) {
            // Run all PHP files in directory
            $files = glob(rtrim($fileOrDir, '/') . '/*.php');
            foreach ($files as $file) {
                echo "Running test: $file\n";
                passthru("php " . escapeshellarg($file), $exitCode);
                if ($exitCode !== 0) {
                    echo "Test failed: $file\n";
                }
            }
        } else {
            // Single file
            echo "Running test: $fileOrDir\n";
            passthru("php " . escapeshellarg($fileOrDir), $exitCode);
            if ($exitCode !== 0) {
                echo "Test failed: $fileOrDir\n";
            }
        }

        return 0;
    }
}
