<?php

namespace App\Jobs;

use App\Models\Alumno;
use App\Models\Promocion;
use App\Models\WhatsappLog;
use App\Services\WhatsAppService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public int $tries    = 3;
    public int $backoff  = 60;

    public function __construct(
        public Promocion $promocion,
        public Alumno $alumno
    ) {}

    public function handle(WhatsAppService $whatsapp): void
    {
        $this->alumno->refresh();

        if ($this->alumno->opt_out) {
            return;
        }

        $telefono = $this->alumno->telefonoWhatsapp();

        if (!$telefono) {
            WhatsappLog::create([
                'alumno_id' => $this->alumno->id,
                'telefono'  => 'sin_telefono',
                'tipo'      => 'error',
                'mensaje'   => 'Alumno sin teléfono registrado',
                'payload'   => ['promocion_id' => $this->promocion->id],
            ]);

            $this->actualizarPivot('fallido', null);
            return;
        }

        try {
            $nombre    = $this->alumno->alumnos()->first()?->name ?? 'estudiante';
            $mensajeId = $whatsapp->enviarPromocion($telefono, $this->promocion, $nombre);
        } catch (\RuntimeException $e) {
            WhatsappLog::create([
                'alumno_id' => $this->alumno->id,
                'telefono'  => $telefono,
                'tipo'      => 'error',
                'mensaje'   => $e->getMessage(),
                'payload'   => ['promocion_id' => $this->promocion->id],
            ]);

            $this->actualizarPivot('fallido', null);
            return;
        }

        WhatsappLog::create([
            'alumno_id' => $this->alumno->id,
            'telefono'  => $telefono,
            'tipo'      => 'enviado',
            'mensaje'   => $this->promocion->titulo,
            'payload'   => ['promocion_id' => $this->promocion->id, 'whatsapp_id' => $mensajeId],
        ]);

        $this->actualizarPivot('enviado', $mensajeId);
    }

    private function actualizarPivot(string $status, ?string $mensajeId): void
    {
        $this->promocion->alumnos()->updateExistingPivot($this->alumno->id, [
            'status_envio'        => $status,
            'enviado_at'          => now(),
            'whatsapp_mensaje_id' => $mensajeId,
        ]);
    }
}
