<?php

declare(strict_types=1);

namespace App\Console\Commands;

use Hypervel\Console\Command;
use Hypervel\Support\Facades\DB;
use Hypervel\Support\Facades\Redis;
use Throwable;

class CheckConnectionsCommand extends Command
{
    protected ?string $signature = 'app:check-connections {--detail : Show extended info (Redis INFO, DB version)}';

    protected string $description = 'Test DB and Redis connectivity; exits 1 if any check fails (use in startup scripts)';

    public function handle(): int
    {
        $allOk = true;

        // ── MySQL ─────────────────────────────────────────────────────────────
        $this->line('');
        $this->line('<fg=cyan>Checking MySQL...</>');
        try {
            $t = microtime(true);
            $result = DB::select('SELECT 1 AS ok');
            $ms = round((microtime(true) - $t) * 1000, 1);
            if ($result && $result[0]->ok === 1) {
                $this->line("  <fg=green>✓</> Connected ({$ms}ms)");
                if ($this->option('detail')) {
                    $ver = DB::select('SELECT VERSION() AS v');
                    $this->line('  Version: ' . ($ver[0]->v ?? '?'));
                    $pool = config('database.connections.mysql.pool');
                    $this->line('  Pool max_connections: ' . ($pool['max_connections'] ?? '?'));
                    $this->line('  Pool heartbeat: ' . ($pool['heartbeat'] ?? '?'));
                    $this->line('  Pool max_idle_time: ' . ($pool['max_idle_time'] ?? '?'));
                }
            } else {
                $this->line('  <fg=red>✗</> Unexpected response from SELECT 1');
                $allOk = false;
            }
        } catch (Throwable $e) {
            $this->line('  <fg=red>✗</> ' . $e->getMessage());
            $allOk = false;
        }

        // ── Redis ─────────────────────────────────────────────────────────────
        $this->line('');
        $this->line('<fg=cyan>Checking Redis...</>');
        try {
            $t = microtime(true);
            $pong = Redis::ping();
            $ms = round((microtime(true) - $t) * 1000, 1);
            $this->line("  <fg=green>✓</> PING → {$pong} ({$ms}ms)");
            if ($this->option('detail')) {
                $info = Redis::info();
                $this->line('  Version: ' . ($info['redis_version'] ?? '?'));
                $this->line('  Used memory: ' . ($info['used_memory_human'] ?? '?'));
                $this->line('  Connected clients: ' . ($info['connected_clients'] ?? '?'));
            }
        } catch (Throwable $e) {
            $this->line('  <fg=red>✗</> ' . $e->getMessage());
            $allOk = false;
        }

        // ── Summary ───────────────────────────────────────────────────────────
        $this->line('');
        if ($allOk) {
            $this->info('All connections OK.');
            return 0;
        }

        $this->error('One or more connections FAILED. Check the errors above.');
        return 1;
    }
}
