#!/usr/bin/env node

/**
 * Test script to verify backward compatibility
 * Tests the existing server against our new TypeScript implementation
 */

const http = require('http');

// Test configuration
const OLD_SERVER_PORT = 3333; // Current running server
const TEST_URL = 'github.com';

async function makeRequest(port, path, method = 'GET', body = null) {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'localhost',
      port: port,
      path: path,
      method: method,
      headers: {
        'Content-Type': 'application/json',
      },
    };

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

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

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

async function testBackwardCompatibility() {
  console.log('🧪 Testing Backward Compatibility...\n');

  try {
    // Test 1: Legacy /api/track endpoint
    console.log('1. Testing legacy /api/track endpoint...');
    const legacyResult = await makeRequest(OLD_SERVER_PORT, '/api/track', 'POST', {
      url: TEST_URL,
      method: 'GET'
    });
    console.log(`   Status: ${legacyResult.status}`);
    console.log(`   Response: ${JSON.stringify(legacyResult.data, null, 2).substring(0, 200)}...`);

    // Test 2: /api/v1/track POST endpoint
    console.log('\n2. Testing /api/v1/track POST endpoint...');
    const v1PostResult = await makeRequest(OLD_SERVER_PORT, '/api/v1/track', 'POST', {
      url: TEST_URL,
      method: 'GET'
    });
    console.log(`   Status: ${v1PostResult.status}`);
    console.log(`   Response: ${JSON.stringify(v1PostResult.data, null, 2).substring(0, 200)}...`);

    // Test 3: /api/v1/track GET endpoint
    console.log('\n3. Testing /api/v1/track GET endpoint...');
    const v1GetResult = await makeRequest(OLD_SERVER_PORT, `/api/v1/track?url=${TEST_URL}&method=GET`, 'GET');
    console.log(`   Status: ${v1GetResult.status}`);
    console.log(`   Response: ${JSON.stringify(v1GetResult.data, null, 2).substring(0, 200)}...`);

    // Test 4: Health check
    console.log('\n4. Testing health check...');
    const healthResult = await makeRequest(OLD_SERVER_PORT, '/health', 'GET');
    console.log(`   Status: ${healthResult.status}`);
    console.log(`   Response: ${JSON.stringify(healthResult.data, null, 2)}`);

    console.log('\n✅ All backward compatibility tests completed!');
    console.log('\nNext step: Test with new TypeScript implementation using Docker.');

  } catch (error) {
    console.error('\n❌ Error during testing:', error.message);
    console.log('\nThis is expected if the server is not running.');
    console.log('Start the existing server with: node index.js');
  }
}

// Run tests
testBackwardCompatibility();
