<?php

namespace App\Console\Commands;

use App\Models\DnsQueryUsage;
use App\Models\User;
use App\Services\DnsQueryLimitService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class EnforceDnsLimits extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'dns:enforce-limits
        {--user= : Verifică doar pentru un utilizator specific (ID)}
        {--dry-run : Doar afișează ce ar face, fără a aplica acțiuni}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Verifică și aplică limitele de query-uri DNS pentru toți utilizatorii';

    /**
     * Execute the console command.
     */
    public function handle(DnsQueryLimitService $limitService)
    {
        $this->info('🔍 Verificare limite query-uri DNS...');
        $startTime = microtime(true);
        $dryRun = $this->option('dry-run');

        if ($dryRun) {
            $this->warn('⚠️ Mod DRY RUN - nu se vor aplica acțiuni');
        }

        // Filtrează utilizatorii
        $query = User::whereHas('plan', function ($q) {
            $q->where(function ($subQ) {
                $subQ->whereNotNull('dns_queries_limit')
                     ->where('dns_queries_limit', '>', 0);
            })->orWhere(function ($subQ) {
                $subQ->whereNotNull('dns_queries_limit_daily')
                     ->where('dns_queries_limit_daily', '>', 0);
            });
        });

        if ($userId = $this->option('user')) {
            $query->where('id', $userId);
        }

        $users = $query->with('plan')->get();
        $this->info("📊 Verificare {$users->count()} utilizatori cu limite active");

        if ($users->isEmpty()) {
            $this->info('✓ Nu există utilizatori cu limite de verificat');
            return Command::SUCCESS;
        }

        $results = [
            'checked' => 0,
            'exceeded_daily' => 0,
            'exceeded_monthly' => 0,
            'actions_taken' => 0,
            'users_suspended' => [],
            'users_notified' => [],
        ];

        $this->newLine();
        $headers = ['User', 'Plan', 'Zilnic', 'Lunar', 'Acțiune'];
        $rows = [];

        foreach ($users as $user) {
            $results['checked']++;

            $usage = DnsQueryUsage::getOrCreateForCurrentMonth($user->id);
            $status = $usage->checkLimitStatus();
            $plan = $user->plan;

            // Calculează procentajele
            $dailyPct = $plan->hasDailyLimit()
                ? round(($usage->daily_query_count / $plan->dns_queries_limit_daily) * 100, 1)
                : null;
            $monthlyPct = $plan->hasMonthlyLimit()
                ? round(($usage->query_count / $plan->dns_queries_limit) * 100, 1)
                : null;

            $dailyStr = $dailyPct !== null ? "{$dailyPct}%" : 'N/A';
            $monthlyStr = $monthlyPct !== null ? "{$monthlyPct}%" : 'N/A';
            $actionStr = '-';

            if ($status['exceeded']) {
                if ($status['type'] === 'daily') {
                    $results['exceeded_daily']++;
                } else {
                    $results['exceeded_monthly']++;
                }

                $actionStr = match($status['action']) {
                    'refuse' => '🚫 REFUSED',
                    'suspend' => '⛔ SUSPEND',
                    'notify' => 'ℹ️ Notify',
                    default => $status['action'],
                };

                if (!$dryRun && $status['action'] === 'suspend') {
                    $limitService->suspendUserZones($user, 'Limită de query-uri DNS depășită');
                    $results['users_suspended'][] = $user->email;
                    $results['actions_taken']++;
                }

                if (!$dryRun) {
                    $results['users_notified'][] = $user->email;
                }
            }

            $rows[] = [
                $user->email,
                $plan->name,
                $dailyStr,
                $monthlyStr,
                $actionStr,
            ];
        }

        $this->table($headers, $rows);
        $this->newLine();

        // Sumar
        $this->info('📈 Sumar:');
        $this->info("  • Utilizatori verificați: {$results['checked']}");

        if ($results['exceeded_daily'] > 0) {
            $this->warn("  • Depășiri limită zilnică: {$results['exceeded_daily']}");
        } else {
            $this->info("  • Depășiri limită zilnică: 0");
        }

        if ($results['exceeded_monthly'] > 0) {
            $this->warn("  • Depășiri limită lunară: {$results['exceeded_monthly']}");
        } else {
            $this->info("  • Depășiri limită lunară: 0");
        }

        if (!$dryRun && !empty($results['users_suspended'])) {
            $this->error("  • Utilizatori suspendați: " . implode(', ', $results['users_suspended']));
        }

        $duration = round(microtime(true) - $startTime, 2);
        $this->info("⏱️ Durata: {$duration}s");

        Log::info('Verificare limite DNS completată', [
            'checked' => $results['checked'],
            'exceeded_daily' => $results['exceeded_daily'],
            'exceeded_monthly' => $results['exceeded_monthly'],
            'actions_taken' => $results['actions_taken'],
            'duration' => $duration,
        ]);

        return Command::SUCCESS;
    }
}
