<?php

namespace Modules\WhatsApp\Entities\Services\Drivers;

use Modules\WhatsApp\Entities\Contracts\WaTransport;
use Modules\WhatsApp\Entities\Services\SendResult;
use Modules\WhatsApp\Entities\WaChannel;
use Modules\WhatsApp\Entities\WaMessage;

/**
 * WhatsApp-Web channel paired by QR scan, driven by a standalone Node bridge
 * (Baileys) that runs on the server — one process per channel.
 *
 * This transport is PULL-based: the bridge polls GET /api/whatsapp/agent/outbox
 * for 'queued' messages, sends them through the live socket, then reports the
 * outcome via POST /api/whatsapp/agent/ack. So "send" here only stages the
 * message for the bridge — it never blocks on the actual WhatsApp delivery.
 *
 * Crucially, if the bridge socket is down (QR lost / phone offline) the message
 * is held for retry, never dropped. When the operator re-scans the QR the
 * channel goes 'active' again and the held messages flow out.
 */
class WhatsAppWebDriver implements WaTransport
{
    public function send(WaChannel $channel, WaMessage $message): SendResult
    {
        if ($channel->status === 'disabled') {
            return SendResult::fail('Channel is disabled.');
        }

        // No live, recently-seen bridge → hold the message until it reconnects.
        if (!$channel->isBridgeOnline() || $channel->status !== 'active') {
            return SendResult::retry('WhatsApp-Web bridge offline — awaiting QR reconnect.');
        }

        // Stage for the bridge to pick up on its next outbox poll.
        $message->forceFill([
            'status'    => 'queued',
            'queued_at' => now(),
            'error'     => null,
        ])->save();

        return SendResult::handoff();
    }
}
