<?php

namespace App\Notifications;

use App\Models\DnsZone;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class DnsAnomalyDetected extends Notification implements ShouldQueue
{
    use Queueable;

    protected DnsZone $zone;
    protected array $anomalies;

    /**
     * Create a new notification instance.
     */
    public function __construct(DnsZone $zone, array $anomalies)
    {
        $this->zone = $zone;
        $this->anomalies = $anomalies;
    }

    /**
     * Get the notification's delivery channels.
     */
    public function via(object $notifiable): array
    {
        return ['database', 'mail'];
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        $criticalCount = count(array_filter($this->anomalies, fn($a) => $a['severity'] === 'critical'));
        $warningCount = count($this->anomalies) - $criticalCount;

        $mail = (new MailMessage)
            ->subject("⚠️ Anomalii DNS detectate pentru {$this->zone->domain}")
            ->greeting("Alertă DNS pentru {$this->zone->domain}")
            ->line("Au fost detectate anomalii în traficul DNS pentru domeniul {$this->zone->domain}:");

        foreach ($this->anomalies as $anomaly) {
            $icon = $anomaly['severity'] === 'critical' ? '🔴' : '🟡';
            $mail->line("{$icon} {$anomaly['message']}");
        }

        $mail->line('')
            ->action('Vezi statistici detaliate', route('dns-zones.statistics', $this->zone->domain))
            ->line('Recomandare: Verifică configurația DNS și monitorizează traficul.');

        if ($criticalCount > 0) {
            $mail->line('')
                ->line("⚠️ Atenție: {$criticalCount} probleme critice necesită atenție imediată!");
        }

        return $mail;
    }

    /**
     * Get the array representation of the notification.
     */
    public function toArray(object $notifiable): array
    {
        $criticalCount = count(array_filter($this->anomalies, fn($a) => $a['severity'] === 'critical'));

        return [
            'type' => 'dns_anomaly',
            'domain' => $this->zone->domain,
            'zone_id' => $this->zone->id,
            'anomalies_count' => count($this->anomalies),
            'critical_count' => $criticalCount,
            'anomalies' => $this->anomalies,
            'message' => $criticalCount > 0
                ? "🔴 {$criticalCount} probleme critice detectate pentru {$this->zone->domain}"
                : "⚠️ " . count($this->anomalies) . " anomalii detectate pentru {$this->zone->domain}",
            'url' => route('dns-zones.statistics', $this->zone->domain)
        ];
    }
}
