/**
 * Test script to fetch device configuration from Auvik API
 * Usage: npx tsx scripts/test-auvik-config.ts YNGHYNSWP19
 */

import { AuvikClient } from '../lib/services/auvik-client';

interface AuvikConfigurationResponse {
  data: Array<{
    type: string;
    id: string;
    attributes: {
      deviceId: string;
      backupDate: string;
      configType: string;
      configText?: string;
      configSize?: number;
    };
  }>;
  links?: {
    next?: string;
  };
}

async function testAuvikConfiguration(hostname: string) {
  console.log(`\n=== Testing Auvik Configuration API for: ${hostname} ===\n`);

  // Initialize Auvik client
  const config = {
    apiUrl: process.env.AUVIK_API_URL || 'https://auvikapi.us1.my.auvik.com',
    apiUser: process.env.AUVIK_API_USER || '',
    apiKey: process.env.AUVIK_API_KEY || '',
  };

  if (!config.apiUser || !config.apiKey) {
    console.error('Error: AUVIK_API_USER and AUVIK_API_KEY environment variables must be set');
    process.exit(1);
  }

  const client = new AuvikClient(config);

  try {
    // Step 1: Find all devices and locate the one with matching hostname
    console.log('Step 1: Fetching all devices to find matching hostname...');
    const devices = await client.getAllDevices();
    console.log(`Found ${devices.length} total devices`);

    const matchingDevice = devices.find(
      (d) => d.deviceName.toLowerCase() === hostname.toLowerCase()
    );

    if (!matchingDevice) {
      console.error(`\nDevice not found with hostname: ${hostname}`);
      console.log('\nAvailable devices:');
      devices.forEach((d) => {
        console.log(`  - ${d.deviceName} (${d.deviceType}) - ${d.id}`);
      });
      process.exit(1);
    }

    console.log(`\n✓ Found device: ${matchingDevice.deviceName}`);
    console.log(`  Device ID: ${matchingDevice.id}`);
    console.log(`  Type: ${matchingDevice.deviceType}`);
    console.log(`  Tenant: ${matchingDevice.tenantName || matchingDevice.tenantId}`);
    console.log(`  Status: ${matchingDevice.onlineStatus}`);
    console.log(`  IP Addresses: ${matchingDevice.ipAddresses.join(', ')}`);

    // Step 2: Try to fetch device configuration
    console.log('\nStep 2: Attempting to fetch device configuration...');
    
    // Auvik API endpoint for device configuration
    const configUrl = `${config.apiUrl}/v1/inventory/device/configuration?filter[deviceId]=${matchingDevice.id}`;
    console.log(`Config URL: ${configUrl}`);

    const credentials = Buffer.from(`${config.apiUser}:${config.apiKey}`).toString('base64');
    
    const response = await fetch(configUrl, {
      headers: {
        Authorization: `Basic ${credentials}`,
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error(`\nAPI Error: ${response.status} ${response.statusText}`);
      console.error(`Response: ${errorText}`);
      
      // Try alternative endpoint - device detail
      console.log('\nStep 3: Trying device detail endpoint...');
      const detailUrl = `${config.apiUrl}/v1/inventory/device/detail/${matchingDevice.id}`;
      console.log(`Detail URL: ${detailUrl}`);
      
      const detailResponse = await fetch(detailUrl, {
        headers: {
          Authorization: `Basic ${credentials}`,
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
      });
      
      if (!detailResponse.ok) {
        const detailErrorText = await detailResponse.text();
        console.error(`\nDetail API Error: ${detailResponse.status} ${detailResponse.statusText}`);
        console.error(`Response: ${detailErrorText}`);
      } else {
        const detailData = await detailResponse.json();
        console.log('\n✓ Device Detail Response:');
        console.log(JSON.stringify(detailData, null, 2));
      }
      
      process.exit(1);
    }

    const configData: AuvikConfigurationResponse = await response.json();
    
    console.log('\n✓ Configuration Response:');
    console.log(`Found ${configData.data.length} configuration(s)`);
    
    configData.data.forEach((config, index) => {
      console.log(`\n--- Configuration ${index + 1} ---`);
      console.log(`  Type: ${config.attributes.configType}`);
      console.log(`  Backup Date: ${config.attributes.backupDate}`);
      console.log(`  Size: ${config.attributes.configSize || 'N/A'} bytes`);
      
      if (config.attributes.configText) {
        console.log(`\n  Configuration Text (first 500 chars):`);
        console.log(`  ${config.attributes.configText.substring(0, 500)}...`);
      } else {
        console.log(`  Configuration text not available in response`);
      }
    });

    // Step 4: Try to get the latest configuration backup
    console.log('\n\nStep 4: Fetching latest configuration backup...');
    const backupUrl = `${config.apiUrl}/v1/inventory/device/configuration?filter[deviceId]=${matchingDevice.id}&page[first]=1`;
    console.log(`Backup URL: ${backupUrl}`);
    
    const backupResponse = await fetch(backupUrl, {
      headers: {
        Authorization: `Basic ${credentials}`,
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    });
    
    if (backupResponse.ok) {
      const backupData: AuvikConfigurationResponse = await backupResponse.json();
      console.log('\n✓ Latest Configuration Backup:');
      console.log(JSON.stringify(backupData, null, 2));
    } else {
      const backupError = await backupResponse.text();
      console.error(`\nBackup API Error: ${backupResponse.status} ${backupResponse.statusText}`);
      console.error(`Response: ${backupError}`);
    }

  } catch (error) {
    console.error('\nError:', error);
    process.exit(1);
  }
}

// Get hostname from command line argument
const hostname = process.argv[2];
if (!hostname) {
  console.error('Usage: npx tsx scripts/test-auvik-config.ts <hostname>');
  console.error('Example: npx tsx scripts/test-auvik-config.ts YNGHYNSWP19');
  process.exit(1);
}

testAuvikConfiguration(hostname);
