<?php

namespace App\Commands;

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

class StorageTest extends BaseCommand
{
    protected $group = 'Testing';

    protected $name = 'storage:test';

    protected $description = 'Run policy/endorsement storage tests (local driver and optional live S3).';

    protected $usage = 'storage:test [options]';

    protected $options = [
        '--local'  => 'Run local/helper tests only (skip live S3 integration group).',
        '--s3'     => 'Run live S3 integration tests only (requires AWS env in .env).',
        '--filter' => 'PHPUnit filter pattern, e.g. PolicyStorageHelper.',
    ];

    public function run(array $params)
    {
        $phpunit       = ROOTPATH . 'vendor/bin/phpunit';
        $phpunitConfig = ROOTPATH . 'phpunit.xml.dist';
        $testsPath     = ROOTPATH . 'tests/unit/Storage';

        if (! is_file($phpunit)) {
            CLI::error('PHPUnit not found. Run: composer install');

            return EXIT_ERROR;
        }

        if (! is_file($phpunitConfig)) {
            CLI::error('PHPUnit config not found: ' . $phpunitConfig);

            return EXIT_ERROR;
        }

        if (! is_dir($testsPath)) {
            CLI::error('Storage tests directory not found: ' . $testsPath);

            return EXIT_ERROR;
        }

        $previousDirectory = getcwd() ?: ROOTPATH;
        chdir(ROOTPATH);

        $command = [
            PHP_BINARY,
            $phpunit,
            '-c',
            $phpunitConfig,
            $testsPath,
            '--testdox',
            '--colors=always',
            '--no-coverage',
        ];

        if (CLI::getOption('local')) {
            $command[] = '--exclude-group';
            $command[] = 's3-integration';
        } elseif (CLI::getOption('s3')) {
            $command[] = '--group';
            $command[] = 's3-integration';
        }

        $filter = CLI::getOption('filter');

        if (is_string($filter) && $filter !== '') {
            $command[] = '--filter';
            $command[] = $filter;
        }

        $display = implode(' ', array_map(static fn ($part) => escapeshellarg((string) $part), $command));
        CLI::write('Running storage tests...', 'green');
        CLI::write($display, 'dark_gray');

        passthru($display, $exitCode);

        chdir($previousDirectory);

        if ($exitCode === 0) {
            CLI::write('Storage tests passed.', 'green');
        } else {
            CLI::error('Storage tests failed with exit code ' . $exitCode);
        }

        return $exitCode;
    }
}
