<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Services\WhatsAppService;
use Illuminate\Support\Facades\Log;

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

    public $tries = 3;
    public $backoff = [5, 10, 30]; // segundos

    protected $number;
    protected $message;
    protected $type;
    protected $title;
    protected $url;

    /**
     * Create a new job instance.
     */
    public function __construct($number, $message, $type = 'text', $title = null, $url = null)
    {
        $this->number = $number;
        $this->message = $message;
        $this->type = $type;
        $this->title = $title;
        $this->url = $url;
    }

    /**
     * Execute the job.
     */
    public function handle(WhatsAppService $whatsapp): void
    {
        try {
            if ($this->type === 'post_notification' && $this->title && $this->url) {
                $result = $whatsapp->sendPostNotification(
                    $this->number,
                    $this->title,
                    $this->url,
                    'new_post'
                );
            } else {
                $result = $whatsapp->sendText($this->number, $this->message);
            }

            if (!$result['success']) {
                Log::warning('WhatsApp notification failed', [
                    'number' => $this->number,
                    'error' => $result['message'] ?? 'Unknown error'
                ]);

                // Se falhou, lançar exceção para tentar novamente
                throw new \Exception($result['message'] ?? 'Failed to send WhatsApp message');
            }

            Log::info('WhatsApp notification sent', [
                'number' => $this->number,
                'type' => $this->type
            ]);

        } catch (\Exception $e) {
            Log::error('WhatsApp job error', [
                'number' => $this->number,
                'error' => $e->getMessage()
            ]);

            throw $e; // Re-throw para retry
        }
    }

    /**
     * Handle a job failure.
     */
    public function failed(\Throwable $exception): void
    {
        Log::error('WhatsApp notification job failed permanently', [
            'number' => $this->number,
            'error' => $exception->getMessage()
        ]);
    }
}

