<?php

namespace Modules\WhatsApp\Console;

use Illuminate\Console\Command;
use Modules\WhatsApp\Entities\Services\WaSender;
use Modules\WhatsApp\Entities\WaMessage;

/**
 * Safety net for the durability guarantee: re-dispatches any outbound message
 * that is still 'pending' and due, in case its queue job was lost (worker
 * restart/outage) or the message was created without a live worker.
 *
 * Only touches messages whose throttle gate (available_at) has passed, so it
 * never breaks the anti-ban pacing. Idempotent — re-dispatching a pending
 * message that is already queued is harmless because the job re-checks status.
 *
 * Schedule: every minute.
 */
class SweepPendingMessages extends Command
{
    protected $signature = 'whatsapp:sweep {--limit=500}';
    protected $description = 'Re-dispatch any due WhatsApp messages still pending delivery.';

    public function handle(WaSender $sender): int
    {
        $limit = (int) $this->option('limit');

        $due = WaMessage::where('direction', 'out')
            ->where('status', 'pending')
            ->where(function ($q) {
                $q->whereNull('available_at')->orWhere('available_at', '<=', now());
            })
            ->orderBy('id')
            ->limit($limit)
            ->get();

        foreach ($due as $message) {
            $sender->dispatchFor($message);
        }

        $this->info("Re-dispatched {$due->count()} pending WhatsApp message(s).");
        return self::SUCCESS;
    }
}
