const http = require('http');

console.log('🔍 Testing API endpoints directly...');

// Test login endpoint
const options = {
  hostname: 'localhost',
  port: 3000,
  path: '/api/drift/login',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
};

console.log('📡 Testing /api/drift/login...');

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', () => {
    console.log('📦 Response body:');
    console.log(data);
    
    if (res.statusCode === 200) {
      try {
        const result = JSON.parse(data);
        console.log('✅ Login successful:', result);
        
        // Now test balance endpoint
        testBalance();
      } catch (e) {
        console.log('❌ Failed to parse JSON response:', e.message);
      }
    } else {
      console.log('❌ Login failed with status:', res.statusCode);
    }
  });
});

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

req.end();

function testBalance() {
  console.log('\n📡 Testing /api/drift/balance...');
  
  const balanceOptions = {
    hostname: 'localhost',
    port: 3000,
    path: '/api/drift/balance',
    method: 'GET',
  };

  const balanceReq = http.request(balanceOptions, (res) => {
    console.log(`Balance Status: ${res.statusCode}`);
    
    let data = '';
    res.on('data', (chunk) => {
      data += chunk;
    });
    
    res.on('end', () => {
      console.log('📦 Balance Response:');
      console.log(data);
      
      try {
        const result = JSON.parse(data);
        console.log('✅ Balance result:', result);
      } catch (e) {
        console.log('❌ Failed to parse balance JSON:', e.message);
      }
      
      // Test positions
      testPositions();
    });
  });

  balanceReq.on('error', (e) => {
    console.error('❌ Balance request error:', e.message);
  });

  balanceReq.end();
}

function testPositions() {
  console.log('\n📡 Testing /api/drift/positions...');
  
  const positionsOptions = {
    hostname: 'localhost',
    port: 3000,
    path: '/api/drift/positions',
    method: 'GET',
  };

  const positionsReq = http.request(positionsOptions, (res) => {
    console.log(`Positions Status: ${res.statusCode}`);
    
    let data = '';
    res.on('data', (chunk) => {
      data += chunk;
    });
    
    res.on('end', () => {
      console.log('📦 Positions Response:');
      console.log(data);
      
      try {
        const result = JSON.parse(data);
        console.log('✅ Positions result:', result);
      } catch (e) {
        console.log('❌ Failed to parse positions JSON:', e.message);
      }
    });
  });

  positionsReq.on('error', (e) => {
    console.error('❌ Positions request error:', e.message);
  });

  positionsReq.end();
}
