<?php

namespace App\Jobs;

use App\Models\CrmMessage;
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;

/**
 * Delivers a single queued CrmMessage.
 *
 * With QUEUE_CONNECTION=sync (the default) this runs inline. Point the queue
 * at the database driver and run `php artisan queue:work` to blast hundreds of
 * parents without blocking the web request or hitting Meta's rate limits.
 */
class SendCrmMessage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public int $backoff = 20; // seconds between retries (Cloud API rate limits)

    public function __construct(public int $messageId)
    {
    }

    public function handle(WhatsAppService $wa): void
    {
        $msg = CrmMessage::find($this->messageId);
        if ($msg && in_array($msg->status, ['queued', 'failed'])) {
            $wa->send($msg);
        }
    }
}
