#!/usr/bin/env node

/**
 * Registry Integration Test
 * 
 * Tests the registry API integration to ensure the firmware registry functionality works correctly
 */

const http = require('http');
const fs = require('fs');
const path = require('path');

const REGISTRY_URL = 'http://localhost:8080';
const TIMEOUT = 10000; // 10 seconds

function makeRequest(path, method = 'GET', body = null, isFormData = false) {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'localhost',
      port: 8080,
      path: path,
      method: method,
      headers: {}
    };

    if (body && !isFormData) {
      options.headers['Content-Type'] = 'application/json';
    }

    const req = http.request(options, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        try {
          const jsonData = JSON.parse(data);
          resolve({ status: res.statusCode, data: jsonData });
        } catch (error) {
          resolve({ status: res.statusCode, data: data });
        }
      });
    });

    req.on('error', (error) => {
      reject(error);
    });

    req.setTimeout(TIMEOUT, () => {
      req.destroy();
      reject(new Error('Request timeout'));
    });

    if (body) {
      req.write(body);
    }
    
    req.end();
  });
}

async function testRegistryHealth() {
  console.log('Testing registry health endpoint...');
  try {
    const response = await makeRequest('/health');
    if (response.status === 200 && response.data.status === 'healthy') {
      console.log('✅ Registry health check passed');
      return true;
    } else {
      console.log('❌ Registry health check failed:', response);
      return false;
    }
  } catch (error) {
    console.log('❌ Registry health check failed:', error.message);
    return false;
  }
}

async function testListFirmware() {
  console.log('Testing list firmware endpoint...');
  try {
    const response = await makeRequest('/firmware');
    if (response.status === 200 && Array.isArray(response.data)) {
      console.log('✅ List firmware endpoint works, found', response.data.length, 'firmware entries');
      return true;
    } else {
      console.log('❌ List firmware endpoint failed:', response);
      return false;
    }
  } catch (error) {
    console.log('❌ List firmware endpoint failed:', error.message);
    return false;
  }
}

async function testUploadFirmware() {
  console.log('Testing upload firmware endpoint...');
  
  // Create a small test firmware file
  const testFirmwareContent = Buffer.from('test firmware content');
  const metadata = {
    name: 'test-firmware',
    version: '1.0.0',
    labels: {
      platform: 'esp32',
      app: 'test'
    }
  };

  try {
    // Create multipart form data
    const boundary = '----formdata-test-boundary';
    const formData = [
      `--${boundary}`,
      'Content-Disposition: form-data; name="metadata"',
      'Content-Type: application/json',
      '',
      JSON.stringify(metadata),
      `--${boundary}`,
      'Content-Disposition: form-data; name="firmware"; filename="test.bin"',
      'Content-Type: application/octet-stream',
      '',
      testFirmwareContent.toString(),
      `--${boundary}--`
    ].join('\r\n');

    const response = await makeRequest('/firmware', 'POST', formData, true);
    
    if (response.status === 201 && response.data.success) {
      console.log('✅ Upload firmware endpoint works');
      return true;
    } else {
      console.log('❌ Upload firmware endpoint failed:', response);
      return false;
    }
  } catch (error) {
    console.log('❌ Upload firmware endpoint failed:', error.message);
    return false;
  }
}

async function testDownloadFirmware() {
  console.log('Testing download firmware endpoint...');
  try {
    const response = await makeRequest('/firmware/test-firmware/1.0.0');
    if (response.status === 200) {
      console.log('✅ Download firmware endpoint works');
      return true;
    } else {
      console.log('❌ Download firmware endpoint failed:', response);
      return false;
    }
  } catch (error) {
    console.log('❌ Download firmware endpoint failed:', error.message);
    return false;
  }
}

async function runTests() {
  console.log('Starting Registry Integration Tests...\n');
  
  const tests = [
    { name: 'Health Check', fn: testRegistryHealth },
    { name: 'List Firmware', fn: testListFirmware },
    { name: 'Upload Firmware', fn: testUploadFirmware },
    { name: 'Download Firmware', fn: testDownloadFirmware }
  ];

  let passed = 0;
  let total = tests.length;

  for (const test of tests) {
    console.log(`\n--- ${test.name} ---`);
    try {
      const result = await test.fn();
      if (result) {
        passed++;
      }
    } catch (error) {
      console.log(`❌ ${test.name} failed with error:`, error.message);
    }
  }

  console.log(`\n--- Test Results ---`);
  console.log(`Passed: ${passed}/${total}`);
  
  if (passed === total) {
    console.log('🎉 All tests passed! Registry integration is working correctly.');
    process.exit(0);
  } else {
    console.log('⚠️  Some tests failed. Please check the registry server.');
    process.exit(1);
  }
}

// Run tests if this script is executed directly
if (require.main === module) {
  runTests().catch(error => {
    console.error('Test runner failed:', error);
    process.exit(1);
  });
}

module.exports = {
  testRegistryHealth,
  testListFirmware,
  testUploadFirmware,
  testDownloadFirmware,
  runTests
};
