#!/usr/bin/env node
// Test script for text transport testing
// Tests sending 1 large and 1 small text from JavaScript serviceA to JavaScript serviceB
// Uses NATSBridge.js smartsend with "text" type

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

// Configuration
const SUBJECT = "/NATSBridge_text_test";
const NATS_URL = "nats.yiem.cc";
const FILESERVER_URL = "http://192.168.88.104:8080";

// Create correlation ID for tracing
const correlation_id = uuid4();

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

// File upload handler for plik server
async function plik_upload_handler(fileserver_url, dataname, data, correlation_id) {
    // Get upload ID
    const url_getUploadID = `${fileserver_url}/upload`;
    const headers = {
        "Content-Type": "application/json"
    };
    const body = JSON.stringify({ OneShot: true });
    
    let response = await fetch(url_getUploadID, {
        method: "POST",
        headers: headers,
        body: body
    });
    
    if (!response.ok) {
        throw new Error(`Failed to get upload ID: ${response.status} ${response.statusText}`);
    }
    
    const responseJson = await response.json();
    const uploadid = responseJson.id;
    const uploadtoken = responseJson.uploadToken;
    
    // Upload file
    const formData = new FormData();
    const blob = new Blob([data], { type: "application/octet-stream" });
    formData.append("file", blob, dataname);
    
    response = await fetch(`${fileserver_url}/file/${uploadid}`, {
        method: "POST",
        headers: {
            "X-UploadToken": uploadtoken
        },
        body: formData
    });
    
    if (!response.ok) {
        throw new Error(`Failed to upload file: ${response.status} ${response.statusText}`);
    }
    
    const fileResponseJson = await response.json();
    const fileid = fileResponseJson.id;
    
    const url = `${fileserver_url}/file/${uploadid}/${fileid}/${encodeURIComponent(dataname)}`;
    
    return {
        status: response.status,
        uploadid: uploadid,
        fileid: fileid,
        url: url
    };
}

// Sender: Send text via smartsend
async function test_text_send() {
    // Create a small text (will use direct transport)
    const small_text = "Hello, this is a small text message. Testing direct transport via NATS.";
    
    // Create a large text (will use link transport if > 1MB)
    // Generate a larger text (~2MB to ensure link transport)
    const large_text_lines = [];
    for (let i = 0; i < 50000; i++) {
        large_text_lines.push(`Line ${i}: This is a sample text line with some content to pad the size. `);
    }
    const large_text = large_text_lines.join("");
    
    // Test data 1: small text
    const data1 = { dataname: "small_text", data: small_text, type: "text" };
    
    // Test data 2: large text
    const data2 = { dataname: "large_text", data: large_text, type: "text" };
    
    // Use smartsend with text type
    // For small text: will use direct transport (Base64 encoded UTF-8)
    // For large text: will use link transport (uploaded to fileserver)
    const { env, env_json_str } = await smartsend(
        SUBJECT,
        [data1, data2],
        {
            natsUrl: NATS_URL,
            fileserverUrl: FILESERVER_URL,
            fileserverUploadHandler: plik_upload_handler,
            sizeThreshold: 1_000_000,
            correlationId: correlation_id,
            msgPurpose: "chat",
            senderName: "text_sender",
            receiverName: "",
            receiverId: "",
            replyTo: "",
            replyToMsgId: "",
            isPublish: true  // Publish the message to NATS
        }
    );
    
    log_trace(`Sent message with ${env.payloads.length} payloads`);
    
    // Log transport type for each payload
    for (let i = 0; i < env.payloads.length; i++) {
        const payload = env.payloads[i];
        log_trace(`Payload ${i + 1} ('${payload.dataname}'):`);
        log_trace(`  Transport: ${payload.transport}`);
        log_trace(`  Type: ${payload.type}`);
        log_trace(`  Size: ${payload.size} bytes`);
        log_trace(`  Encoding: ${payload.encoding}`);
        
        if (payload.transport === "link") {
            log_trace(`  URL: ${payload.data}`);
        }
    }
}

// Run the test
console.log("Starting text transport test...");
console.log(`Correlation ID: ${correlation_id}`);

// Run sender
console.log("start smartsend for text");
test_text_send();

console.log("Test completed.");