<?php

namespace App\Jobs;

use App\Domain\WhatsApp\WhatsAppManager;
use App\Models\WaMessage;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public int $tries = 1; // retry logic is in WhatsAppManager, not the queue

    public function __construct(public int $messageId)
    {
    }

    public function handle(WhatsAppManager $manager): void
    {
        // Bypass tenant scope: the queue worker has no request-bound tenant.
        $message = WaMessage::query()->withoutGlobalScope('tenant')->find($this->messageId);
        if ($message) {
            $manager->deliver($message);
        }
    }
}
