<?php

app_require('config.php');
app_require('classes/db.php');
app_require('classes/redis.php');
app_require('classes/superuser_system_status_service.php');

use classes\db;
use classes\redis;
use classes\superuser_system_status_service;

beforeEach(function (): void {
    if (!integration_enabled()) {
        test()->markTestSkipped('Set RUN_INTEGRATION_TESTS=1 to run system status integration tests.');
    }

    $GLOBALS['response'] = new class {
        public function internal_server_error(string $message): void
        {
            throw new RuntimeException($message);
        }
    };

    $GLOBALS['db'] = new db($GLOBALS['CONFIG_DB']);
    $GLOBALS['db']->connect();

    if (!defined('redis') && isset($GLOBALS['REDIS_CONFIG']) && is_array($GLOBALS['REDIS_CONFIG'])) {
        try {
            define('redis', (new redis())->connect());
        } catch (Throwable) {
            // Redis-specific expectations are skipped below when the client is unavailable.
        }
    }
});

afterEach(function (): void {
    if (isset($GLOBALS['db']) && $GLOBALS['db'] instanceof db) {
        $GLOBALS['db']->close();
    }
});

it('can probe the configured database in integration mode', function (): void {
    $probe = (new superuser_system_status_service())->probeDatabase();

    expect($probe['status'])->toBe('ok');
    expect($probe['database'])->not->toBe('');
    expect($probe)->toHaveKey('server_version');
});

it('can probe redis in integration mode when configured', function (): void {
    if (!isset($GLOBALS['REDIS_CONFIG']) || !defined('redis')) {
        test()->markTestSkipped('Redis is not configured in this integration environment.');
    }

    $probe = (new superuser_system_status_service())->probeRedis();

    expect(in_array($probe['status'], ['ok', 'degraded', 'down'], true))->toBeTrue();
    expect($probe)->toHaveKey('checked_at');
});

it('can probe minio in integration mode when configured', function (): void {
    if (!isset($GLOBALS['MINIO']) || !is_array($GLOBALS['MINIO']) || empty($GLOBALS['MINIO']['endpoint'])) {
        test()->markTestSkipped('MinIO is not configured in this integration environment.');
    }

    $probe = (new superuser_system_status_service())->probeMinio();

    expect(in_array($probe['status'], ['ok', 'degraded', 'down'], true))->toBeTrue();
    expect($probe)->toHaveKey('buckets');
});
