<?php

namespace App\Listeners;

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

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

        if (!$adminEmail) {
            return;
        }

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

