<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\DnsZone;
use App\Services\DnsStatisticsService;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class CollectDnsStatistics extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'dns:collect-statistics {--date= : Data pentru care să colecteze statistici (Y-m-d)}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Colectează statistici DNS de pe toate nameserverele pentru toate zonele active';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $date = $this->option('date') ?? Carbon::yesterday()->format('Y-m-d');
        
        $this->info("Colectare statistici DNS pentru data: {$date}");
        
        // Obține toate zonele DNS active care sunt sincronizate cu PowerDNS
        $zones = DnsZone::where('sync_to_powerdns', true)
            ->whereNotNull('powerdns_zone_id')
            ->get();
        
        if ($zones->isEmpty()) {
            $this->warn('Nu există zone DNS sincronizate cu PowerDNS.');
            return 0;
        }
        
        $this->info("Găsite {$zones->count()} zone DNS pentru colectare.");
        
        $statisticsService = new DnsStatisticsService();
        $totalSuccess = 0;
        $totalErrors = 0;
        
        $progressBar = $this->output->createProgressBar($zones->count());
        $progressBar->start();
        
        foreach ($zones as $zone) {
            try {
                $result = $statisticsService->collectStatisticsForDomain($zone, $date);
                
                if ($result['statistics_created'] > 0) {
                    $totalSuccess += $result['statistics_created'];
                    Log::info("Collected statistics for zone {$zone->domain}: {$result['statistics_created']} nameservers");
                } else {
                    $totalErrors++;
                    Log::warning("Failed to collect statistics for zone {$zone->domain}");
                }
                
                if ($result['errors'] > 0) {
                    $totalErrors += $result['errors'];
                }
                
            } catch (\Exception $e) {
                $totalErrors++;
                Log::error("Error collecting statistics for zone {$zone->domain}: " . $e->getMessage());
                $this->error("\nEroare la zona {$zone->domain}: " . $e->getMessage());
            }
            
            $progressBar->advance();
        }
        
        $progressBar->finish();
        $this->newLine(2);
        
        $this->info("✅ Colectare completată!");
        $this->info("   Statistici create: {$totalSuccess}");
        $this->info("   Erori: {$totalErrors}");
        
        return 0;
    }
}
