const { chromium } = require('playwright');

async function testDockerConnectivity() {
  console.log('🔌 Testing Docker app connectivity...');
  
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext();
  const page = await context.newPage();
  
  const testUrls = [
    'http://192.168.0.46:3000/',
    'http://192.168.0.46:3000/login',
    'http://192.168.0.46:3000/login-new',
    'http://192.168.0.46:3000/dashboard'
  ];
  
  const results = [];
  
  for (const url of testUrls) {
    try {
      console.log(`Testing ${url}...`);
      
      const response = await page.goto(url, { timeout: 10000 });
      const status = response.status();
      const finalUrl = page.url();
      const title = await page.title();
      
      results.push({
        url,
        status,
        finalUrl,
        title,
        accessible: status < 400,
        redirected: finalUrl !== url
      });
      
      console.log(`  ✓ Status: ${status}, Final URL: ${finalUrl}`);
      
    } catch (error) {
      results.push({
        url,
        error: error.message,
        accessible: false
      });
      
      console.log(`  ❌ Error: ${error.message}`);
    }
  }
  
  await browser.close();
  
  console.log('\n📊 Connectivity Test Results:');
  console.log('=====================================');
  
  results.forEach(result => {
    console.log(`\n${result.url}:`);
    if (result.accessible) {
      console.log(`  ✅ Accessible (${result.status})`);
      console.log(`  📍 Final URL: ${result.finalUrl}`);
      console.log(`  📝 Title: ${result.title}`);
      if (result.redirected) {
        console.log(`  🔄 Redirected from original URL`);
      }
    } else {
      console.log(`  ❌ Not accessible`);
      console.log(`  💥 Error: ${result.error || 'Unknown error'}`);
    }
  });
  
  const accessibleCount = results.filter(r => r.accessible).length;
  console.log(`\n📈 Summary: ${accessibleCount}/${results.length} URLs accessible`);
  
  return results;
}

if (require.main === module) {
  testDockerConnectivity()
    .then(results => {
      const allAccessible = results.every(r => r.accessible);
      if (allAccessible) {
        console.log('\n🎉 All URLs are accessible! Docker app is working properly.');
      } else {
        console.log('\n⚠️  Some URLs are not accessible. Check Docker setup.');
      }
      process.exit(allAccessible ? 0 : 1);
    })
    .catch(error => {
      console.error('💥 Test failed:', error);
      process.exit(1);
    });
}

module.exports = { testDockerConnectivity };