<?php

namespace App\Jobs;

use App\Models\DnsZone;
use App\Services\DnsStatisticsService;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class CollectDnsZoneStatistics implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Timeout pentru job (2 minute)
     */
    public $timeout = 120;

    /**
     * Număr de încercări în caz de eroare
     */
    public $tries = 3;

    /**
     * Timp de așteptare între încercări (secunde)
     */
    public $backoff = 60;

    /**
     * Zona DNS pentru care se colectează statistici
     */
    protected $zone;

    /**
     * Data pentru care se colectează statistici
     */
    protected $date;

    /**
     * Create a new job instance.
     */
    public function __construct(DnsZone $zone, $date = null)
    {
        $this->zone = $zone;
        $this->date = $date ?? Carbon::yesterday()->format('Y-m-d');
    }

    /**
     * Execute the job.
     */
    public function handle(DnsStatisticsService $service)
    {
        try {
            Log::info("🔄 Începe colectarea statisticilor pentru {$this->zone->domain}", [
                'zone_id' => $this->zone->id,
                'date' => $this->date,
                'attempt' => $this->attempts()
            ]);

            $result = $service->collectStatisticsForDomain($this->zone, $this->date);
            
            Log::info("✅ Statistici colectate cu succes pentru {$this->zone->domain}", [
                'zone_id' => $this->zone->id,
                'date' => $this->date,
                'statistics_created' => $result['statistics_created'] ?? true,
                'total_queries' => $result['total_queries'] ?? 0,
                'attempt' => $this->attempts()
            ]);

        } catch (\Exception $e) {
            Log::error("❌ Eroare colectare statistici pentru {$this->zone->domain}", [
                'zone_id' => $this->zone->id,
                'date' => $this->date,
                'error' => $e->getMessage(),
                'attempt' => $this->attempts(),
                'max_tries' => $this->tries
            ]);

            // Re-throw pentru reÎncearcă automat
            throw $e;
        }
    }

    /**
     * Handle a job failure.
     */
    public function failed(\Throwable $exception)
    {
        Log::error("💀 Job eșuat definitiv pentru {$this->zone->domain}", [
            'zone_id' => $this->zone->id,
            'date' => $this->date,
            'error' => $exception->getMessage(),
            'trace' => $exception->getTraceAsString()
        ]);

        // Aici poți trimite notificare admin dacă vrei
        // notificare::route('mail', config('mail.admin'))->notify(new JobEșuatnotificare(...));
    }

    /**
     * Get the tags that should be assigned to the job.
     */
    public function tags()
    {
        return ['dns-statistics', 'zone:' . $this->zone->id, 'date:' . $this->date];
    }
}
