<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Domain\Database\Models\MysqlDatabase;
use App\Domain\Database\Services\EngineCompatibilityScanner;
use App\Domain\Sysapi\Contracts\SysapiBridge;
use App\Domain\Sysapi\Exceptions\SysapiException;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;

/**
 * Database Version Switcher (Faz R — MySQL/MariaDB upgrade controller).
 *
 * İki adımlı akış (veri kaybı koruması):
 *   1. prepare → full mysqldump + compat scan + go/no-go raporu
 *   2. switch → repo swap + binary install + mysql_upgrade + verify
 *
 * Admin double-confirm zorunlu, üretimde maintenance mode tetiklenmeli.
 */
class DbVersionController extends Controller
{
    /**
     * Hardcoded fallback — sysapi onx-db-versions-available yoksa kullanılır.
     * Üretimde sysapi script repo'lardan canlı versiyon listesi çeker (24h cache).
     *
     * @var array<int, array<string, string>>
     */
    public const TARGETS = [
        ['engine' => 'mariadb', 'version' => '10.6',  'label' => 'MariaDB 10.6 (LTS)',     'note' => 'EOL Tem 2026 — kısa vadeli',  'eol' => '2026-07'],
        ['engine' => 'mariadb', 'version' => '10.11', 'label' => 'MariaDB 10.11 (LTS)',    'note' => 'EOL Şub 2028 — orta vadeli',   'eol' => '2028-02'],
        ['engine' => 'mariadb', 'version' => '11.4',  'label' => 'MariaDB 11.4 (LTS)',     'note' => 'EOL May 2029 — uzun vadeli',  'eol' => '2029-05'],
        ['engine' => 'mariadb', 'version' => '11.8',  'label' => 'MariaDB 11.8 (current)', 'note' => 'En yeni stable',              'eol' => '2027-08'],
        ['engine' => 'mysql',   'version' => '8.0',   'label' => 'MySQL 8.0 (LTS)',        'note' => 'EOL Nis 2026 — Oracle LTS',   'eol' => '2026-04'],
        ['engine' => 'mysql',   'version' => '8.4',   'label' => 'MySQL 8.4 (LTS)',        'note' => 'EOL Nis 2032 — yeni LTS',      'eol' => '2032-04'],
    ];

    public function index(Request $request): Response
    {
        $current = $this->detectCurrent();
        $dbStats = $this->fetchStats();
        $versionList = $this->fetchAvailableVersions(false);

        // Upgrade history — son 10 satır (rollback için en son completed gerekli)
        $history = \Illuminate\Support\Facades\Schema::hasTable('db_version_history')
            ? DB::table('db_version_history')
                ->leftJoin('users', 'users.id', '=', 'db_version_history.initiated_by')
                ->select('db_version_history.*', 'users.name as initiated_by_name')
                ->orderByDesc('db_version_history.started_at')
                ->limit(10)
                ->get()
                ->map(fn ($r) => [
                    'id' => $r->id,
                    'action' => $r->action,
                    'from' => $r->from_engine.' '.$r->from_version,
                    'to' => $r->to_engine.' '.$r->to_version,
                    'status' => $r->status,
                    'downtime_seconds' => $r->downtime_seconds,
                    'database_count' => $r->database_count,
                    'backup_path' => $r->backup_path,
                    'backup_size_mb' => (int) round(($r->backup_size_bytes ?? 0) / 1024 / 1024),
                    'started_at' => $r->started_at,
                    'finished_at' => $r->finished_at,
                    'initiated_by_name' => $r->initiated_by_name,
                    'last_error' => $r->last_error,
                ])
                ->all()
            : [];

        // Rollback adayı: en son completed upgrade satırı (backup_path mevcut)
        $latestUpgrade = collect($history)
            ->first(fn ($h) => $h['action'] === 'upgrade'
                && $h['status'] === 'completed'
                && ! empty($h['backup_path']));

        return Inertia::render('Admin/Mysql/VersionSwitcher', [
            'current' => $current,
            'targets' => $versionList['targets'],
            'targets_source' => $versionList['source'],
            'targets_fetched_at' => $versionList['fetched_at'],
            'stats' => $dbStats,
            'last_preflight' => Cache::get('db_version.preflight'),
            'last_dryrun' => Cache::get('db_version.dryrun'),
            'history' => $history,
            'rollback_candidate' => $latestUpgrade,
        ]);
    }

    /**
     * "Versiyonları Yenile" — sysapi cache bypass + Laravel cache invalidation.
     */
    public function refreshVersions(Request $request): RedirectResponse
    {
        Cache::forget('db_version.available');
        $list = $this->fetchAvailableVersions(true);

        $count = count($list['targets']);
        $source = $list['source'];

        return back()->with('success', "{$count} versiyon listelendi ({$source} kaynak).");
    }

    /**
     * Sysapi onx-db-versions-available çıktısını Laravel cache + sysapi cache
     * üzerinden çek. Sysapi yoksa hardcoded TARGETS'a düş.
     *
     * @return array{targets: array<int, array<string, string>>, source: string, fetched_at: string}
     */
    private function fetchAvailableVersions(bool $force): array
    {
        $cacheKey = 'db_version.available';

        if (! $force) {
            $cached = Cache::get($cacheKey);
            if ($cached !== null) {
                return $cached;
            }
        }

        try {
            /** @var SysapiBridge $sysapi */
            $sysapi = app(SysapiBridge::class);
            $result = $sysapi->run('db-versions-available', ['force' => $force], timeoutSeconds: 30);

            if ($result->successful && ! empty($result->data['targets'])) {
                $list = [
                    'targets' => $result->data['targets'],
                    'source' => $result->data['source'] ?? 'live',
                    'fetched_at' => $result->data['fetched_at'] ?? now()->toIso8601String(),
                ];
                Cache::put($cacheKey, $list, now()->addHours(24));

                return $list;
            }
        } catch (\Throwable $e) {
            Log::info('db-versions-available sysapi unavailable, hardcoded TARGETS', [
                'error' => $e->getMessage(),
            ]);
        }

        // Fallback: hardcoded TARGETS
        return [
            'targets' => self::TARGETS,
            'source' => 'hardcoded',
            'fetched_at' => now()->toIso8601String(),
        ];
    }

    public function prepare(Request $request): RedirectResponse
    {
        $available = $this->fetchAvailableVersions(false)['targets'];
        $engines = collect($available)->pluck('engine')->unique()->all();
        $versions = collect($available)->pluck('version')->unique()->all();

        $validated = $request->validate([
            'target_engine' => ['required', 'string', Rule::in($engines)],
            'target_version' => ['required', 'string', Rule::in($versions)],
        ]);

        try {
            /** @var SysapiBridge $sysapi */
            $sysapi = app(SysapiBridge::class);
            $result = $sysapi->run('db-version-prepare', [
                'target_engine' => $validated['target_engine'],
                'target_version' => $validated['target_version'],
            ], timeoutSeconds: 900);

            if ($result->failed()) {
                Log::warning('db.version_prepare_failed', $validated + ['stderr' => $result->stderr]);

                return back()->with('error', "Preflight başarısız: {$result->stderr}");
            }

            $payload = $result->data + ['prepared_at' => now()->toIso8601String()];

            // Cross-engine compatibility scan — DB başına issue listesi
            $payload['compat_issues'] = $this->runCompatScan(
                $validated['target_engine'],
                $validated['target_version']
            );

            // En az bir 'block' severity varsa go_no_go'yu override et
            $hasBlock = false;
            foreach ($payload['compat_issues'] as $dbScan) {
                if (($dbScan['severity'] ?? 'ok') === 'block') {
                    $hasBlock = true;
                    break;
                }
            }
            if ($hasBlock) {
                $payload['go_no_go'] = 'no-go';
            }

            Cache::put('db_version.preflight', $payload, now()->addHours(2));

            $msg = "Preflight tamam — backup {$payload['backup_size_mb']} MB, tahmini downtime {$payload['estimated_downtime_min']} dk.";
            if (($payload['go_no_go'] ?? 'go') !== 'go') {
                $msg .= ' DİKKAT: uyumluluk sorunları var, raporu incele.';
            }

            return back()->with('success', $msg);
        } catch (SysapiException $e) {
            return back()->with('error', "Preflight başarısız: {$e->getMessage()}");
        }
    }

    public function switch(Request $request): RedirectResponse
    {
        $available = $this->fetchAvailableVersions(false)['targets'];
        $engines = collect($available)->pluck('engine')->unique()->all();
        $versions = collect($available)->pluck('version')->unique()->all();

        $validated = $request->validate([
            'target_engine' => ['required', 'string', Rule::in($engines)],
            'target_version' => ['required', 'string', Rule::in($versions)],
            'confirm_token' => ['required', 'string', 'min:8'],
        ]);

        $preflight = Cache::get('db_version.preflight');
        if (! $preflight || empty($preflight['backup_path'])) {
            return back()->with('error', 'Preflight bulunamadı — önce "Preflight Başlat" çalıştır.');
        }

        // Preflight ile target uyumlu mu?
        if ($preflight['target_engine'] !== $validated['target_engine']
            || $preflight['target_version'] !== $validated['target_version']) {
            return back()->with('error', 'Preflight target değişti — yeniden preflight çalıştır.');
        }

        $current = $this->detectCurrent();
        $startedAt = now();

        // History row aç (status=running) — sysapi sonucuna göre güncellenecek
        $historyId = null;
        if (\Illuminate\Support\Facades\Schema::hasTable('db_version_history')) {
            $historyId = DB::table('db_version_history')->insertGetId([
                'action' => 'upgrade',
                'from_engine' => $current['engine'],
                'from_version' => $current['version'],
                'to_engine' => $validated['target_engine'],
                'to_version' => $validated['target_version'],
                'backup_path' => $preflight['backup_path'],
                'backup_size_bytes' => (int) round(($preflight['backup_size_mb'] ?? 0) * 1024 * 1024),
                'database_count' => (int) ($preflight['database_count'] ?? 0),
                'status' => 'running',
                'initiated_by' => $request->user()?->id,
                'started_at' => $startedAt,
                'metadata' => json_encode(['preflight' => $preflight]),
                'created_at' => $startedAt,
                'updated_at' => $startedAt,
            ]);
        }

        try {
            /** @var SysapiBridge $sysapi */
            $sysapi = app(SysapiBridge::class);
            $result = $sysapi->run('db-version-switch', [
                'target_engine' => $validated['target_engine'],
                'target_version' => $validated['target_version'],
                'backup_path' => $preflight['backup_path'],
                'confirm_token' => $validated['confirm_token'],
            ], timeoutSeconds: 1800);  // 30 dk

            if ($result->failed()) {
                Log::error('db.version_switch_failed', $validated + ['stderr' => $result->stderr]);

                if ($historyId) {
                    DB::table('db_version_history')->where('id', $historyId)->update([
                        'status' => 'failed',
                        'last_error' => $result->stderr,
                        'finished_at' => now(),
                        'updated_at' => now(),
                    ]);
                }

                return back()->with('error', "Upgrade başarısız: {$result->stderr}");
            }

            Cache::forget('db_version.preflight');
            $data = $result->data;

            if ($historyId) {
                DB::table('db_version_history')->where('id', $historyId)->update([
                    'status' => 'completed',
                    'downtime_seconds' => (int) ($data['downtime_seconds'] ?? 0),
                    'finished_at' => now(),
                    'updated_at' => now(),
                ]);
            }

            $msg = "Veritabanı yükseltildi: {$data['from']} → {$data['to']} ({$data['downtime_seconds']}s downtime).";
            $msg .= ' Sorun çıkarsa "Önceki Sürüme Dön" butonu ile rollback yapabilirsin.';

            return back()->with('success', $msg);
        } catch (SysapiException $e) {
            if ($historyId) {
                DB::table('db_version_history')->where('id', $historyId)->update([
                    'status' => 'failed',
                    'last_error' => $e->getMessage(),
                    'finished_at' => now(),
                    'updated_at' => now(),
                ]);
            }
            return back()->with('error', "Upgrade başarısız: {$e->getMessage()}");
        }
    }

    /**
     * Rollback — en son completed upgrade'in backup'ından eski sürüme dön.
     *
     * Akış:
     *   1. db_version_history'den en son completed upgrade satırını çek
     *   2. backup_path geçerli mi kontrol et
     *   3. Onay token doğrula
     *   4. sysapi db-version-rollback çağır (repo swap eski sürüm + binary install
     *      + mysqldump import + mysql_upgrade)
     *   5. Bu satırı 'rolled_back' işaretle, yeni satır action='rollback' ekle
     */
    public function rollback(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'history_id' => ['required', 'integer'],
            'confirm_token' => ['required', 'string', 'min:8'],
        ]);

        if (! \Illuminate\Support\Facades\Schema::hasTable('db_version_history')) {
            return back()->with('error', 'Upgrade geçmişi tablosu yok — önce migrate çalıştır.');
        }

        $row = DB::table('db_version_history')->find($validated['history_id']);

        if (! $row) {
            return back()->with('error', 'Geçmiş kaydı bulunamadı.');
        }

        if ($row->status !== 'completed' || $row->action !== 'upgrade') {
            return back()->with('error', 'Sadece tamamlanmış upgrade işlemleri rollback edilebilir.');
        }

        if (empty($row->backup_path)) {
            return back()->with('error', 'Bu upgrade için backup yolu kayıtlı değil — rollback imkansız.');
        }

        $startedAt = now();

        // Yeni history row: rollback action
        $rollbackId = DB::table('db_version_history')->insertGetId([
            'action' => 'rollback',
            'from_engine' => $row->to_engine,
            'from_version' => $row->to_version,
            'to_engine' => $row->from_engine,
            'to_version' => $row->from_version,
            'backup_path' => $row->backup_path,
            'backup_size_bytes' => $row->backup_size_bytes,
            'database_count' => $row->database_count,
            'status' => 'running',
            'initiated_by' => $request->user()?->id,
            'started_at' => $startedAt,
            'metadata' => json_encode(['rollback_of_history_id' => $row->id]),
            'created_at' => $startedAt,
            'updated_at' => $startedAt,
        ]);

        try {
            /** @var SysapiBridge $sysapi */
            $sysapi = app(SysapiBridge::class);
            $result = $sysapi->run('db-version-rollback', [
                'target_engine' => $row->from_engine,
                'target_version' => $row->from_version,
                'backup_path' => $row->backup_path,
                'confirm_token' => $validated['confirm_token'],
            ], timeoutSeconds: 1800);

            if ($result->failed()) {
                Log::error('db.version_rollback_failed', [
                    'history_id' => $row->id,
                    'stderr' => $result->stderr,
                ]);

                DB::table('db_version_history')->where('id', $rollbackId)->update([
                    'status' => 'failed',
                    'last_error' => $result->stderr,
                    'finished_at' => now(),
                    'updated_at' => now(),
                ]);

                return back()->with('error', "Rollback başarısız: {$result->stderr}");
            }

            $data = $result->data;

            // Rollback başarılı — eski upgrade satırını 'rolled_back' yap
            DB::table('db_version_history')->where('id', $row->id)->update([
                'status' => 'rolled_back',
                'updated_at' => now(),
            ]);

            // Yeni satırı completed
            DB::table('db_version_history')->where('id', $rollbackId)->update([
                'status' => 'completed',
                'downtime_seconds' => (int) ($data['downtime_seconds'] ?? 0),
                'finished_at' => now(),
                'updated_at' => now(),
            ]);

            // Audit log
            try {
                if (\Illuminate\Support\Facades\Schema::hasTable('audit_log')) {
                    DB::table('audit_log')->insert([
                        'user_id' => $request->user()?->id,
                        'action' => 'db.version_rollback',
                        'target_type' => 'db_version_history',
                        'target_id' => $row->id,
                        'ip_address' => $request->ip(),
                        'outcome' => 'success',
                        'metadata' => json_encode([
                            'from' => $row->to_engine.' '.$row->to_version,
                            'to' => $row->from_engine.' '.$row->from_version,
                            'backup_path' => $row->backup_path,
                            'databases_restored' => $data['databases_restored'] ?? null,
                        ]),
                        'created_at' => now(),
                    ]);
                }
            } catch (\Throwable) {}

            return back()->with('success',
                "Rollback tamamlandı: {$row->to_engine} {$row->to_version} → "
                ."{$row->from_engine} {$row->from_version} "
                .'('.($data['downtime_seconds'] ?? 0).'s downtime, '
                .($data['databases_restored'] ?? 0).' DB restore edildi)'
            );
        } catch (SysapiException $e) {
            DB::table('db_version_history')->where('id', $rollbackId)->update([
                'status' => 'failed',
                'last_error' => $e->getMessage(),
                'finished_at' => now(),
                'updated_at' => now(),
            ]);

            return back()->with('error', "Rollback başarısız: {$e->getMessage()}");
        }
    }

    /**
     * Tüm DB'leri tara, engine geçişinde sorun olabilecek yapıları topla.
     *
     * @return array<string, array<string, mixed>>
     */
    private function runCompatScan(string $targetEngine, string $targetVersion): array
    {
        $scanner = new EngineCompatibilityScanner;
        $result = [];

        foreach (MysqlDatabase::all() as $db) {
            $scan = $scanner->scan($db, $targetEngine, $targetVersion);
            if (! empty($scan['issues'])) {
                $result[$db->real_db_name] = [
                    'db_name' => $db->real_db_name,
                    'compatible' => $scan['compatible'],
                    'severity' => $scan['severity'],
                    'summary' => $scan['summary'] ?? null,
                    'issues' => $scan['issues'],
                ];
            }
        }

        return $result;
    }

    /**
     * Auto-fixable issue'ları toplu uygula. Her issue.auto_fix.sql çalıştırılır,
     * sonuç (success/fail) cache'lenmiş preflight'a yazılır.
     *
     * Güvenlik: yalnız scanner tarafından oluşturulan (cache'teki) SQL'ler uygulanır;
     * kullanıcı keyfi SQL gönderemez.
     */
    public function applyAutoFixes(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'db_name' => ['nullable', 'string', 'max:64'],
            'types' => ['nullable', 'array'],
            'types.*' => ['string', 'max:64'],
            'irreversible_ok' => ['boolean'],
        ]);

        $preflight = Cache::get('db_version.preflight');
        if (! $preflight || empty($preflight['compat_issues'])) {
            return back()->with('error', 'Preflight raporu bulunamadı — önce preflight çalıştır.');
        }

        $filterDb = $validated['db_name'] ?? null;
        $filterTypes = $validated['types'] ?? null;
        $irreversibleOk = (bool) ($validated['irreversible_ok'] ?? false);

        $applied = 0;
        $failed = 0;
        $skipped = 0;
        $errors = [];

        foreach ($preflight['compat_issues'] as $dbName => &$dbScan) {
            if ($filterDb !== null && $dbName !== $filterDb) {
                continue;
            }

            foreach ($dbScan['issues'] as &$issue) {
                if (empty($issue['auto_fix']['sql'])) {
                    continue;
                }
                if ($filterTypes !== null && ! in_array($issue['type'], $filterTypes, true)) {
                    continue;
                }
                if (($issue['auto_fix']['irreversible'] ?? false) && ! $irreversibleOk) {
                    $skipped++;
                    $issue['fix_status'] = 'skipped_irreversible';

                    continue;
                }
                if (($issue['fix_status'] ?? '') === 'applied') {
                    continue; // zaten uygulanmış
                }

                try {
                    // Birden fazla statement varsa ayır (sequence dönüşümünde olduğu gibi)
                    $statements = array_filter(array_map('trim', explode(';', $issue['auto_fix']['sql'])));
                    foreach ($statements as $stmt) {
                        if ($stmt !== '') {
                            DB::statement($stmt);
                        }
                    }
                    $issue['fix_status'] = 'applied';
                    $issue['fix_applied_at'] = now()->toIso8601String();
                    $applied++;
                } catch (\Throwable $e) {
                    $issue['fix_status'] = 'failed';
                    $issue['fix_error'] = $e->getMessage();
                    $errors[] = "[{$dbName}/{$issue['type']}] " . $e->getMessage();
                    $failed++;
                    Log::warning('auto_fix_failed', [
                        'db' => $dbName,
                        'type' => $issue['type'],
                        'sql' => $issue['auto_fix']['sql'],
                        'error' => $e->getMessage(),
                    ]);
                }
            }
            unset($issue);
        }
        unset($dbScan);

        Cache::put('db_version.preflight', $preflight, now()->addHours(2));

        $msg = "Auto-fix: {$applied} uygulandı, {$failed} başarısız";
        if ($skipped > 0) {
            $msg .= ", {$skipped} atlandı (geri alınamaz)";
        }
        if ($failed > 0) {
            $msg .= '. Hatalar: ' . implode('; ', array_slice($errors, 0, 3));
            if (count($errors) > 3) {
                $msg .= ' (+' . (count($errors) - 3) . ' more)';
            }

            return back()->with('warning', $msg);
        }

        return back()->with('success', $msg);
    }

    /**
     * Dry-run migration: backup'tan ikinci/paralel DB instance kurar, hedef
     * sürümle test eder, schema/data checksum karşılaştırması yapar. Production
     * DB'yi etkilemez.
     */
    public function dryRun(Request $request): RedirectResponse
    {
        $available = $this->fetchAvailableVersions(false)['targets'];
        $engines = collect($available)->pluck('engine')->unique()->all();
        $versions = collect($available)->pluck('version')->unique()->all();

        $validated = $request->validate([
            'target_engine' => ['required', 'string', Rule::in($engines)],
            'target_version' => ['required', 'string', Rule::in($versions)],
        ]);

        $preflight = Cache::get('db_version.preflight');
        if (! $preflight || empty($preflight['backup_path'])) {
            return back()->with('error', 'Önce Preflight çalıştır (backup gerekli).');
        }

        try {
            /** @var SysapiBridge $sysapi */
            $sysapi = app(SysapiBridge::class);
            $result = $sysapi->run('db-migration-dryrun', [
                'target_engine' => $validated['target_engine'],
                'target_version' => $validated['target_version'],
                'backup_path' => $preflight['backup_path'],
            ], timeoutSeconds: 1800); // 30dk

            if ($result->failed()) {
                Log::warning('db.dryrun_failed', $validated + ['stderr' => $result->stderr]);

                return back()->with('error', "Dry-run başarısız: {$result->stderr}");
            }

            $payload = $result->data;
            Cache::put('db_version.dryrun', $payload + ['ran_at' => now()->toIso8601String()], now()->addHours(2));

            $diff = (int) ($payload['schema_diff_count'] ?? 0);
            $dataDiff = (int) ($payload['data_checksum_mismatches'] ?? 0);
            $msg = "Dry-run tamam — schema diff: {$diff}, data checksum diff: {$dataDiff}";
            if ($diff > 0 || $dataDiff > 0) {
                $msg .= '. Detayları raporda incele.';
            } else {
                $msg .= '. Temiz migration profili (production geçişi düşük riskli).';
            }

            return back()->with('success', $msg);
        } catch (SysapiException $e) {
            return back()->with('error', "Dry-run başarısız: {$e->getMessage()}");
        }
    }

    /**
     * @return array<string, mixed>
     */
    private function detectCurrent(): array
    {
        $version = 'unknown';
        $engine = 'unknown';

        try {
            $row = DB::selectOne('SELECT VERSION() AS v');
            $v = $row?->v ?? '';
            if (str_contains(strtolower($v), 'mariadb')) {
                $engine = 'mariadb';
            } elseif ($v !== '') {
                $engine = 'mysql';
            }
            if (preg_match('/(\d+\.\d+\.\d+)/', $v, $m)) {
                $version = $m[1];
            }
        } catch (\Throwable $e) {
            Log::warning('db.version_detect_failed', ['err' => $e->getMessage()]);
        }

        return [
            'engine' => $engine,
            'version' => $version,
            'label' => $engine === 'mariadb' ? "MariaDB {$version}" : "MySQL {$version}",
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private function fetchStats(): array
    {
        try {
            $dbCount = DB::table('information_schema.SCHEMATA')->count();
            $sizeRow = DB::selectOne('SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024) AS mb
                                       FROM information_schema.TABLES');
            $sizeMb = (int) ($sizeRow?->mb ?? 0);
            $threads = (int) (DB::selectOne("SHOW STATUS LIKE 'Threads_connected'")?->Value ?? 0);
        } catch (\Throwable $e) {
            $dbCount = DB::table('mysql_databases')->count();
            $sizeMb = $dbCount * 60;
            $threads = 0;
        }

        return [
            'database_count' => $dbCount,
            'total_size_mb' => $sizeMb,
            'threads_connected' => $threads,
        ];
    }
}
