#!/usr/bin/env node

/**
 * Test script for Omada API connection
 * Tests authentication and basic API calls
 */

import { OmadaClient, SitesService, DevicesService } from './omada-api/dist/index.js';
import { readFileSync } from 'fs';
import { join } from 'path';
import { homedir } from 'os';

// Load environment variables
const envPath = join(homedir(), '.env');
let envVars = {};

try {
  const envFile = readFileSync(envPath, 'utf8');
  envFile.split('\n').forEach(line => {
    if (line.includes('=') && !line.trim().startsWith('#')) {
      const [key, ...values] = line.split('=');
      if (key && /^[A-Z_][A-Z0-9_]*$/.test(key.trim())) {
        let value = values.join('=').trim();
        if ((value.startsWith('"') && value.endsWith('"')) || 
            (value.startsWith("'") && value.endsWith("'"))) {
          value = value.slice(1, -1);
        }
        envVars[key.trim()] = value;
      }
    }
  });
} catch (error) {
  console.error('Error loading .env file:', error.message);
  process.exit(1);
}

// Get configuration
const baseUrl = envVars.OMADA_CONTROLLER_URL;
const clientId = envVars.OMADA_API_KEY;
const clientSecret = envVars.OMADA_API_SECRET;
const siteId = envVars.OMADA_SITE_ID;
const verifySSL = envVars.OMADA_VERIFY_SSL !== 'false';

if (!baseUrl || !clientId || !clientSecret) {
  console.error('Error: Missing required environment variables');
  console.error('Required: OMADA_CONTROLLER_URL, OMADA_API_KEY, OMADA_API_SECRET');
  process.exit(1);
}

console.log('=== Omada API Connection Test ===\n');
console.log(`Controller URL: ${baseUrl}`);
console.log(`Site ID: ${siteId || 'auto-detect'}`);
console.log(`SSL Verification: ${verifySSL}\n`);

// Create client
const client = new OmadaClient({
  baseUrl,
  clientId,
  clientSecret,
  siteId,
  verifySSL,
});

async function test() {
  try {
    console.log('1. Testing authentication...');
    const auth = client.getAuth();
    const token = await auth.getAccessToken();
    console.log('   ✓ Authentication successful');
    console.log(`   Token: ${token.substring(0, 20)}...\n`);

    console.log('2. Getting site information...');
    const sitesService = new SitesService(client);
    const sites = await sitesService.listSites();
    console.log(`   ✓ Found ${sites.length} site(s)`);
    sites.forEach((site, index) => {
      console.log(`   Site ${index + 1}: ${site.name} (${site.id})`);
    });
    console.log('');

    const effectiveSiteId = siteId || (await client.getSiteId());
    console.log(`3. Using site ID: ${effectiveSiteId}\n`);

    console.log('4. Listing devices...');
    const devicesService = new DevicesService(client);
    const devices = await devicesService.listDevices({ siteId: effectiveSiteId });
    console.log(`   ✓ Found ${devices.length} device(s)`);
    
    if (devices.length > 0) {
      console.log('\n   Devices:');
      devices.forEach((device, index) => {
        console.log(`   ${index + 1}. ${device.name} (${device.type}) - ${device.model}`);
        console.log(`      Status: ${device.status === 1 ? 'Online' : 'Offline'}`);
        console.log(`      IP: ${device.ip || 'N/A'}`);
      });
    } else {
      console.log('   No devices found');
    }

    console.log('\n=== Test completed successfully! ===');
    
  } catch (error) {
    console.error('\n=== Test failed ===');
    console.error('Error:', error.message);
    if (error.stack) {
      console.error('\nStack trace:');
      console.error(error.stack);
    }
    process.exit(1);
  }
}

test();

