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

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

// Configuration
const SUBJECT = "/NATSBridge_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) {
    log_trace(correlation_id, `Uploading ${dataname} to fileserver: ${fileserver_url}`);
    
    // Step 1: Get upload ID and token
    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;
    
    // Step 2: Upload file data
    const url_upload = `${fileserver_url}/file/${uploadid}`;
    
    // Create multipart form data
    const formData = new FormData();
    const blob = new Blob([data], { type: "application/octet-stream" });
    formData.append("file", blob, dataname);
    
    response = await fetch(url_upload, {
        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;
    
    // Build the download URL
    const url = `${fileserver_url}/file/${uploadid}/${fileid}/${encodeURIComponent(dataname)}`;
    
    log_trace(correlation_id, `Uploaded to URL: ${url}`);
    
    return {
        status: response.status,
        uploadid: uploadid,
        fileid: fileid,
        url: url
    };
}

// Sender: Send large binary file via smartsend
async function test_large_binary_send() {
    // Read the large file as binary data
    const fs = require('fs');
    
    // Test data 1
    const file_path1 = './testFile_large.zip';
    const file_data1 = fs.readFileSync(file_path1);
    const filename1 = 'testFile_large.zip';
    const data1 = { dataname: filename1, data: file_data1, type: "binary" };
    
    // Test data 2
    const file_path2 = './testFile_small.zip';
    const file_data2 = fs.readFileSync(file_path2);
    const filename2 = 'testFile_small.zip';
    const data2 = { dataname: filename2, data: file_data2, type: "binary" };
    
    // Use smartsend with binary type - will automatically use link transport
    // if file size exceeds the threshold (1MB by default)
    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: "sender",
            receiverName: "",
            receiverId: "",
            replyTo: "",
            replyToMsgId: "",
            isPublish: true  // Publish the message to NATS
        }
    );
    
    log_trace(`Sent message with transport: ${env.payloads[0].transport}`);
    log_trace(`Envelope type: ${env.payloads[0].type}`);
    
    // Check if link transport was used
    if (env.payloads[0].transport === "link") {
        log_trace("Using link transport - file uploaded to HTTP server");
        log_trace(`URL: ${env.payloads[0].data}`);
    } else {
        log_trace("Using direct transport - payload sent via NATS");
    }
}

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

// Run sender first
console.log("start smartsend");
test_large_binary_send();

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

console.log("Test completed.");