/**
 * Node.js Test Suite for Local Connector Agent Buffer & Checkpoint System
 */

const assert = require('assert');
const fs = require('fs');
const path = require('path');
const { loadQueue, saveQueue, loadCheckpoint, saveCheckpoint } = require('../src/agent');

console.log(`\n======================================================`);
console.log(` 🧪 NODE.JS LOCAL CONNECTOR AGENT UNIT TESTS`);
console.log(`======================================================\n`);

try {
  // Test 1: Queue Persistence
  console.log(`[TEST 1/3] Testing Queue Persistence...`);
  const sampleQueue = [
    { pin: '1001', scan: '2026-08-09 08:00:00', verify: 'fingerprint' },
    { pin: '1002', scan: '2026-08-09 08:05:00', verify: 'fingerprint' }
  ];
  saveQueue(sampleQueue);
  const loaded = loadQueue();
  assert.strictEqual(loaded.length, 2, 'Loaded queue should contain 2 items');
  assert.strictEqual(loaded[0].pin, '1001', 'First PIN should match 1001');
  console.log(` [PASS] Queue Persistence Verified OK`);

  // Test 2: Checkpoint Manager
  console.log(`[TEST 2/3] Testing Checkpoint Manager...`);
  const sampleCheckpoint = { last_synced_timestamp: '2026-08-09 08:05:00' };
  saveCheckpoint(sampleCheckpoint);
  const loadedCp = loadCheckpoint();
  assert.strictEqual(loadedCp.last_synced_timestamp, '2026-08-09 08:05:00', 'Checkpoint timestamp should match');
  console.log(` [PASS] Checkpoint Manager Verified OK`);

  // Test 3: Cleanup Test Files
  console.log(`[TEST 3/3] Cleaning up test data state...`);
  saveQueue([]);
  assert.strictEqual(loadQueue().length, 0, 'Queue should be empty after cleanup');
  console.log(` [PASS] Cleanup Verified OK`);

  console.log(`\n======================================================`);
  console.log(` SUCCESS: ALL NODE.JS CONNECTOR TESTS PASSED 100%`);
  console.log(`======================================================\n`);
  process.exit(0);
} catch (err) {
  console.error(`\n [FAIL] Node.js Test Error: ${err.message}`);
  process.exit(1);
}
