<?php

declare(strict_types=1);

require_once __DIR__ . '/../vendor/codeigniter4/framework/system/Test/bootstrap.php';

use CodeIgniter\Config\DotEnv;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\MigrationRunner;
use Config\Database;
use Config\Migrations as MigrationsConfig;

if (defined('CLQMS_PHPUNIT_BOOTSTRAPPED') || ENVIRONMENT !== 'testing') {
    return;
}

define('CLQMS_PHPUNIT_BOOTSTRAPPED', true);

(new DotEnv(ROOTPATH))->load();

$db = Database::connect('tests');
$forge = Database::forge('tests');

$db->query('SET FOREIGN_KEY_CHECKS=0');
foreach ($db->listTables() as $table) {
    $forge->dropTable($table, true);
}
$db->query('SET FOREIGN_KEY_CHECKS=1');

$migrationsConfig = config(MigrationsConfig::class);
$migrationRunner = new MigrationRunner($migrationsConfig, 'tests');
try {
    $migrationRunner->latest();
} catch (DatabaseException $e) {
    $message = $e->getMessage();
    if (strpos($message, 'already exists') === false) {
        throw $e;
    }
}

$initialBufferLevel = ob_get_level();
ob_start();
try {
    $seeder = Database::seeder('tests');
    $seeder->setSilent(true)->call('DBSeeder');
} finally {
    while (ob_get_level() > $initialBufferLevel) {
        ob_end_clean();
    }
}
