/**
 * Diagnostic & Verification Script for Local Connector Agent
 */
const axios = require('axios');
require('dotenv').config();

const config = {
  laravelUrl: (process.env.LARAVEL_API_URL || 'http://localhost').replace(/\/+$/, ''),
  token: process.env.CONNECTOR_TOKEN || 'SK_LNK_SMKN1_9238491823',
  machineId: process.env.MACHINE_ID || 1,
  machineIp: process.env.MACHINE_IP || '192.168.0.106',
  serialNumber: process.env.SERIAL_NUMBER || '616231023290570',
};

async function runDiagnostic() {
  console.log(`\n======================================================`);
  console.log(` 🩺 LOCAL CONNECTOR DIAGNOSTIC SUITE`);
  console.log(` Target Laravel: ${config.laravelUrl}`);
  console.log(` Machine IP:     ${config.machineIp}`);
  console.log(` Serial Number:  ${config.serialNumber}`);
  console.log(`======================================================\n`);

  // Step 1: Heartbeat Diagnostic
  console.log(`[TEST 1/2] Sending Heartbeat Ping...`);
  try {
    const hbRes = await axios.post(
      `${config.laravelUrl}/api/connector/heartbeat`,
      {
        machine_id: config.machineId,
        ip_address: config.machineIp,
        serial_number: config.serialNumber,
        device_info: { test_mode: true, runner: 'test-agent.js' },
      },
      {
        headers: {
          'X-Connector-Token': config.token,
          'Authorization': `Bearer ${config.token}`,
        },
        timeout: 8000,
      }
    );
    console.log(` [PASS] Heartbeat Accepted: ${hbRes.data.message} (Correlation: ${hbRes.data.correlation_id})`);
  } catch (err) {
    console.error(` [FAIL] Heartbeat Failed: ${err.response ? JSON.stringify(err.response.data) : err.message}`);
  }

  // Step 2: Attendance Push Diagnostic
  console.log(`\n[TEST 2/2] Sending Test Attendance Push...`);
  try {
    const pushRes = await axios.post(
      `${config.laravelUrl}/api/connector/push-attendance`,
      {
        machine_id: config.machineId,
        ip_address: config.machineIp,
        serial_number: config.serialNumber,
        logs: [
          {
            pin: '1001',
            scan: new Date().toISOString().replace('T', ' ').substring(0, 19),
            verify: 'fingerprint',
          },
        ],
      },
      {
        headers: {
          'X-Connector-Token': config.token,
          'Authorization': `Bearer ${config.token}`,
        },
        timeout: 8000,
      }
    );
    console.log(` [PASS] Push Accepted: ${pushRes.data.message} (Inserted: ${pushRes.data.inserted_count}, Duplicates: ${pushRes.data.duplicate_count})`);
  } catch (err) {
    console.error(` [FAIL] Push Failed: ${err.response ? JSON.stringify(err.response.data) : err.message}`);
  }

  console.log(`\n======================================================\n`);
}

runDiagnostic();
