#!/opt/cpanel/ea-php85/root/usr/bin/php
<?php

declare(strict_types=1);

require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/tests/harness.php';

if (PHP_SAPI !== 'cli') {
    fwrite(STDERR, "This script must be run from the command line.\n");
    exit(1);
}

// Make sure the schema is up to date before running suites.
try {
    contextia_test_bootstrap()->migrationRunner()->run();
} catch (Throwable $e) {
    fwrite(STDERR, sprintf("Unable to prepare database for tests: %s\n", $e->getMessage()));
    exit(1);
}

$suites = glob(dirname(__DIR__) . '/tests/*_test.php') ?: [];
sort($suites);

/*
 * A suite that cannot even be LOADED must be loud. A fatal at require time —
 * a helper defined in another suite that sorts later, a typo in a use — used
 * to end the whole run right there, printing only the suite header: the
 * remaining suites never ran and the summary never appeared, which reads
 * exactly like a suite with no tests in it.
 */
register_shutdown_function(static function (): void {
    $error = error_get_last();
    if ($error !== null && ($error['type'] & (E_ERROR | E_PARSE | E_COMPILE_ERROR | E_CORE_ERROR)) !== 0) {
        fwrite(STDERR, sprintf(
            "\nSUITE NAO CARREGOU: %s\n  em %s:%d\n  As suites seguintes NAO rodaram.\n",
            $error['message'],
            $error['file'],
            $error['line']
        ));
    }
});

foreach ($suites as $suite) {
    echo "\n== " . basename($suite) . " ==\n";
    require $suite;
}

exit(contextia_test_summary());
