<?php

namespace App\Notifications;

use App\Models\Setting;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Collection;

/**
 * Alerta crítica al administrador cuando hay muchos fallos en el servicio de correo.
 */
class AdminCriticalEmailFailure extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public float $failureRate,
        public Collection $recentFailures
    ) {}

    public function via(object $notifiable): array
    {
        // Database first to ensure in-app notification is saved even if mail fails
        return ['database', 'mail'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        $appName = Setting::get('app_name', 'CoachPro');
        $subject = "🚨 ALERTA: Alta tasa de fallos en correos ({$this->failureRate}%)";

        $mail = (new MailMessage)
            ->subject($subject)
            ->error() // Red header
            ->greeting('⚠️ Alerta del Sistema de Correos')
            ->line("Se ha detectado una tasa de fallos elevada en el envío de correos de {$appName}.")
            ->line('')
            ->line("**Tasa de fallos (últimas 24h):** {$this->failureRate}%")
            ->line('')
            ->line('---')
            ->line('## 📋 Últimos Errores Registrados')
            ->line('');

        foreach ($this->recentFailures->take(5) as $failure) {
            $time = $failure->created_at->format('H:i');
            $type = $failure->notification_type;
            $error = substr($failure->error_message ?? 'Error desconocido', 0, 100);
            
            $mail->line("- **{$time}** | {$type}");
            $mail->line("  Error: _{$error}_");
        }

        $mail->line('')
             ->line('---')
             ->line('## 🔧 Acciones Recomendadas')
             ->line('')
             ->line('1. Verificar configuración SMTP en `.env`')
             ->line('2. Comprobar credenciales del servicio de correo')
             ->line('3. Revisar límites de envío del proveedor')
             ->line('4. Verificar conectividad del servidor')
             ->line('5. Revisar logs en `storage/logs/laravel.log`')
             ->line('')
             ->action('Ver Panel de Administración', route('admin.settings.index'))
             ->line('')
             ->line('Esta alerta no se repetirá en la próxima hora.')
             ->salutation("Sistema de Monitoreo de {$appName}");

        return $mail;
    }

    public function toArray(object $notifiable): array
    {
        return [
            'type' => 'critical_email_failure',
            'failure_rate' => $this->failureRate,
            'failures_count' => $this->recentFailures->count(),
            'message' => "🚨 ALERTA: {$this->failureRate}% de correos fallando en las últimas 24 horas",
            'title' => 'Alerta crítica de correos',
            'url' => route('admin.settings.index'),
        ];
    }
}
