#!/usr/bin/env node

/**
 * Test the improved Drift API connection
 */

const http = require('http');

function testAPI() {
  console.log('🚀 Testing improved Drift API connection...');
  
  const postData = JSON.stringify({});
  
  const options = {
    hostname: 'localhost',
    port: 3000,
    path: '/api/drift/login',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(postData)
    },
    timeout: 30000 // 30 second timeout
  };

  const req = http.request(options, (res) => {
    console.log(`📡 Status: ${res.statusCode}`);
    console.log(`📋 Headers:`, res.headers);

    let data = '';
    res.on('data', (chunk) => {
      data += chunk;
    });

    res.on('end', () => {
      try {
        const result = JSON.parse(data);
        console.log('✅ API Response:');
        console.log(JSON.stringify(result, null, 2));
        
        if (result.isLoggedIn) {
          console.log('🎉 SUCCESS: Drift connection is working!');
        } else {
          console.log('⚠️ Not logged in, but API is responding. Error:', result.error);
        }
      } catch (e) {
        console.log('📄 Raw response:', data);
      }
    });
  });

  req.on('error', (e) => {
    console.error('❌ Request error:', e.message);
  });

  req.on('timeout', () => {
    console.error('⏰ Request timed out after 30 seconds');
    req.destroy();
  });

  req.write(postData);
  req.end();
}

// Wait a bit more for container to be ready
setTimeout(() => {
  testAPI();
}, 5000);

console.log('⏳ Waiting 5 seconds for container to be ready...');
