<?php

namespace App\Listeners;

use App\Events\OrdenLavanderiaTerminada;
use App\Mail\OrdenLavanderiaTerminadaAdmin;
use App\Models\NotificacionLog;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;

class EnviarCorreoOrdenLavanderiaTerminadaAdmin implements ShouldQueue
{
    public function handle(OrdenLavanderiaTerminada $event): void
    {
        $adminEmail = config('mail.from.address');

        if (!$adminEmail) {
            return;
        }

        try {
            Mail::to($adminEmail)->send(new OrdenLavanderiaTerminadaAdmin($event->orden));
            NotificacionLog::create([
                'orden_lavanderia_id' => $event->orden->id,
                'tipo' => 'terminada_admin',
                'destinatario' => $adminEmail,
                'enviado_at' => now(),
                'estado' => NotificacionLog::ESTADO_ENVIADO,
            ]);
        } catch (Throwable $e) {
            NotificacionLog::create([
                'orden_lavanderia_id' => $event->orden->id,
                'tipo' => 'terminada_admin',
                'destinatario' => $adminEmail,
                'enviado_at' => now(),
                'estado' => NotificacionLog::ESTADO_FALLIDO,
                'mensaje_error' => $e->getMessage(),
            ]);
            Log::warning('No se pudo enviar correo terminada_admin; se omite en este entorno.', [
                'orden_lavanderia_id' => $event->orden->id,
                'destinatario' => $adminEmail,
                'error' => $e->getMessage(),
            ]);
        }
    }
}
