// Check if QR code needs to be scanned again
async function checkQRCode() {
  console.log('📱 CHECKING WHATSAPP WEB CONNECTION STATUS');
  console.log('='.repeat(50));
  
  try {
    // Check if we can get QR code (means disconnected)
    console.log('1️⃣ Checking if QR code is available...');
    
    const qrResponse = await fetch('http://localhost:3005/api/default/auth/qr', {
      headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
    });
    
    if (qrResponse.ok) {
      const qrData = await qrResponse.json();
      console.log('🚨 QR CODE IS AVAILABLE - WhatsApp Web is DISCONNECTED!');
      console.log('');
      console.log('🔧 SOLUTION:');
      console.log('1. Open this URL in your browser: http://localhost:3005/api/default/auth/qr');
      console.log('2. Open WhatsApp on your phone');
      console.log('3. Go to: Menu > Linked Devices > Link a Device');
      console.log('4. Scan the QR code shown in the browser');
      console.log('5. Wait for "WORKING" status');
      console.log('');
      console.log('💡 This explains why messages show "sent" but you don\'t receive them!');
      console.log('   WAHA can queue messages but can\'t deliver when WhatsApp Web is disconnected.');
      
      return false; // Not connected
    } else {
      console.log('✅ QR code not available - WhatsApp Web should be connected');
      
      // Let's restart the session to refresh the connection
      console.log('\n2️⃣ Restarting session to refresh connection...');
      
      const restartResponse = await fetch('http://localhost:3005/api/sessions/default/restart', {
        method: 'POST',
        headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
      });
      
      if (restartResponse.ok) {
        console.log('✅ Session restart initiated');
        console.log('⏳ Waiting 10 seconds for reconnection...');
        
        await new Promise(resolve => setTimeout(resolve, 10000));
        
        // Check status again
        const statusResponse = await fetch('http://localhost:3005/api/sessions', {
          headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
        });
        
        if (statusResponse.ok) {
          const sessions = await statusResponse.json();
          const defaultSession = sessions.find(s => s.name === 'default');
          console.log(`📱 New status: ${defaultSession?.status}`);
          console.log(`📱 Presence: ${defaultSession?.presence || 'unknown'}`);
          
          if (defaultSession?.status === 'WORKING' && defaultSession?.presence !== 'offline') {
            console.log('✅ Connection refreshed successfully!');
            
            // Send another test message
            console.log('\n3️⃣ Sending post-restart test message...');
            
            const testMessage = {
              session: 'default',
              chatId: defaultSession.me?.id,
              text: `🔄 POST-RESTART TEST MESSAGE

Connection refreshed at: ${new Date().toLocaleString()}

If you receive this, the WhatsApp Web connection is now working properly!

From: Clinera (Post-Restart Test)`
            };
            
            const sendResponse = await fetch('http://localhost:3005/api/sendText', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'X-Api-Key': '992659f827564646ba3ab95ead50adc9'
              },
              body: JSON.stringify(testMessage)
            });
            
            if (sendResponse.ok) {
              const result = await sendResponse.json();
              console.log(`✅ Post-restart message sent: ${result.key?.id}`);
              console.log('📱 CHECK YOUR WHATSAPP NOW!');
            }
            
            return true; // Connected
          } else {
            console.log('❌ Still not properly connected after restart');
            return false;
          }
        }
      } else {
        console.log('❌ Session restart failed:', await restartResponse.text());
      }
    }
    
  } catch (error) {
    console.error('❌ QR check failed:', error);
    return false;
  }
}

// Also provide manual instructions
async function showManualInstructions() {
  console.log('\n📋 MANUAL TROUBLESHOOTING STEPS:');
  console.log('='.repeat(40));
  console.log('');
  console.log('If messages still not received:');
  console.log('');
  console.log('1️⃣ CHECK WHATSAPP APP ON YOUR PHONE:');
  console.log('   - Is WhatsApp app running?');
  console.log('   - Does phone have internet connection?');
  console.log('   - Any pending app updates?');
  console.log('');
  console.log('2️⃣ CHECK WHATSAPP WEB:');
  console.log('   - Open web.whatsapp.com in browser');
  console.log('   - Is it connected or showing QR code?');
  console.log('   - If QR code: scan it again');
  console.log('');
  console.log('3️⃣ CHECK MESSAGE SETTINGS:');
  console.log('   - WhatsApp > Settings > Privacy');
  console.log('   - Check if messages from unknown numbers are blocked');
  console.log('   - Check notification settings');
  console.log('');
  console.log('4️⃣ NUCLEAR OPTION - RESTART EVERYTHING:');
  console.log('   docker restart waha');
  console.log('   Then scan QR code again: http://localhost:3005/api/default/auth/qr');
  console.log('');
  console.log('5️⃣ TEST WITH DIFFERENT NUMBER:');
  console.log('   - Try sending to a different WhatsApp number');
  console.log('   - This will confirm if the issue is specific to your number');
}

checkQRCode()
  .then(connected => {
    if (!connected) {
      console.log('\n🚨 CONNECTION ISSUE DETECTED!');
      console.log('The main problem is WhatsApp Web disconnection.');
      console.log('Follow the QR code scanning steps above.');
    } else {
      console.log('\n✅ CONNECTION LOOKS GOOD!');
      console.log('If you still don\'t receive messages, try manual troubleshooting.');
    }
    
    showManualInstructions();
  })
  .catch(console.error);