#!/usr/bin/env node
// Test script for large payload testing using binary transport
// Tests receiving a large file (> 1MB) via smartsend with binary type

const { smartreceive, log_trace } = require('./src/NATSBridge');

// Configuration
const SUBJECT = "/NATSBridge_test";
const NATS_URL = "nats.yiem.cc";

// Helper: Log with correlation ID
function log_trace(message) {
    const timestamp = new Date().toISOString();
    console.log(`[${timestamp}] ${message}`);
}

// Receiver: Listen for messages and verify large payload handling
async function test_large_binary_receive() {
    // Connect to NATS
    const { connect } = require('nats');
    const nc = await connect({ servers: [NATS_URL] });
    
    // Subscribe to the subject
    const sub = nc.subscribe(SUBJECT);
    
    for await (const msg of sub) {
        log_trace(`Received message on ${msg.subject}`);
        
        // Use NATSBridge.smartreceive to handle the data
        const result = await smartreceive(
            msg,
            {
                maxRetries: 5,
                baseDelay: 100,
                maxDelay: 5000
            }
        );
        
        // Result is an envelope dictionary with payloads field
        // Access payloads with result.payloads
        for (const { dataname, data, type } of result.payloads) {
            if (data instanceof Uint8Array || Array.isArray(data)) {
                const file_size = data.length;
                log_trace(`Received ${file_size} bytes of binary data for '${dataname}' of type ${type}`);
                
                // Save received data to a test file
                const fs = require('fs');
                const output_path = `./new_${dataname}`;
                fs.writeFileSync(output_path, Buffer.from(data));
                log_trace(`Saved received data to ${output_path}`);
            } else {
                log_trace(`Received unexpected data type for '${dataname}': ${typeof data}`);
            }
        }
    }
    
    // Keep listening for 10 seconds
    setTimeout(() => {
        nc.close();
        process.exit(0);
    }, 120000);
}

// Run the test
console.log("Starting large binary payload test...");

// Run receiver
console.log("testing smartreceive");
test_large_binary_receive();

console.log("Test completed.");