<?php

namespace Modules\WhatsApp\Console;

use Illuminate\Console\Command;
use Modules\WhatsApp\Entities\Services\ChannelHealthService;
use Modules\WhatsApp\Entities\WaChannel;

/**
 * Detects WhatsApp-Web (QR) channels whose Node bridge stopped heart-beating
 * and flags them disconnected so admins are prompted to re-scan. Held messages
 * are kept and resent automatically on reconnect.
 *
 * Schedule: every minute.
 */
class MarkStaleChannelsOffline extends Command
{
    protected $signature = 'whatsapp:health-check';
    protected $description = 'Flag WhatsApp-Web channels whose bridge heartbeat is stale.';

    public function handle(ChannelHealthService $health): int
    {
        $timeout = (int) config('whatsapp.health.heartbeat_timeout', 90);
        $cutoff = now()->subSeconds($timeout);

        $stale = WaChannel::where('driver', 'web')
            ->where('status', 'active')
            ->where(function ($q) use ($cutoff) {
                $q->whereNull('last_heartbeat_at')->orWhere('last_heartbeat_at', '<', $cutoff);
            })
            ->get();

        foreach ($stale as $channel) {
            $health->flagDisconnected($channel, 'Bridge heartbeat timed out.');
            $this->warn("Channel #{$channel->id} ({$channel->label}) flagged disconnected.");
        }

        $this->info("Checked WhatsApp channel health. {$stale->count()} flagged.");
        return self::SUCCESS;
    }
}
