<?php

namespace App\Console\Commands;

use App\Models\NameServer;
use App\Services\NameServerService;
use Illuminate\Console\Command;

class CheckNameServersHealth extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'nameservers:check-health {--all : Check all servers} {--id= : Check specific server by ID}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Verifică starea de sănătate a serverelor Name Server și salvează statistici';

    protected $nameServerService;

    public function __construct(NameServerService $nameServerService)
    {
        parent::__construct();
        $this->nameServerService = $nameServerService;
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('🔍 Începe verificarea Name Servers...');
        $this->newLine();

        // Determină ce servere să verifice
        if ($serverId = $this->option('id')) {
            $servers = NameServer::where('id', $serverId)->get();
            if ($servers->isEmpty()) {
                $this->error("❌ Serverul cu ID {$serverId} nu a fost găsit!");
                return 1;
            }
        } else {
            // Verifică doar serverele active
            $servers = NameServer::where('is_active', true)->get();
        }

        if ($servers->isEmpty()) {
            $this->warn('⚠️  Nu există servere NS active de verificat.');
            return 0;
        }

        $this->info("📊 Găsite {$servers->count()} servere de verificat");
        $this->newLine();

        $results = [
            'online' => 0,
            'offline' => 0,
            'degraded' => 0,
        ];

        $progressBar = $this->output->createProgressBar($servers->count());
        $progressBar->start();

        foreach ($servers as $server) {
            try {
                $result = $this->nameServerService->checkHealth($server);
                
                $results[$result['status']]++;
                
                $progressBar->advance();
            } catch (\Exception $e) {
                $this->newLine();
                $this->error("❌ Eroare la verificarea {$server->hostname}: " . $e->getMessage());
                $progressBar->advance();
            }
        }

        $progressBar->finish();
        $this->newLine(2);

        // Afișare rezumat
        $this->info('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        $this->info('📊 REZUMAT VERIFICARE:');
        $this->newLine();
        
        $this->line("  🟢 Online:   <fg=green>{$results['online']}</>");
        $this->line("  🔴 Offline:  <fg=red>{$results['offline']}</>");
        $this->line("  🟡 Degraded: <fg=yellow>{$results['degraded']}</>");
        
        $this->newLine();
        $this->info('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        
        $totalChecked = $results['online'] + $results['offline'] + $results['degraded'];
        $successRate = $totalChecked > 0 ? round(($results['online'] / $totalChecked) * 100, 2) : 0;
        
        $this->info("✅ Verificare completă! Success rate: {$successRate}%");
        $this->newLine();

        return 0;
    }
}
