// Debug actual message delivery issues
async function debugDelivery() {
  console.log('🔍 DEBUGGING WHY MESSAGES NOT REACHING OBAID');
  console.log('='.repeat(60));
  
  try {
    // 1. Check WAHA session details
    console.log('1️⃣ Checking WAHA session status...');
    const sessionResponse = await fetch('http://localhost:3005/api/sessions', {
      headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
    });
    
    if (sessionResponse.ok) {
      const sessions = await sessionResponse.json();
      const defaultSession = sessions.find(s => s.name === 'default');
      
      if (defaultSession) {
        console.log('📱 WAHA Session Details:');
        console.log(`   Status: ${defaultSession.status}`);
        console.log(`   Connected as: ${defaultSession.me?.pushName || 'Unknown'}`);
        console.log(`   Phone: ${defaultSession.me?.id || 'Unknown'}`);
        console.log(`   LID: ${defaultSession.me?.lid || 'N/A'}`);
        
        if (defaultSession.status !== 'WORKING') {
          console.log('❌ PROBLEM: WAHA session not in WORKING status!');
          return;
        }
      } else {
        console.log('❌ PROBLEM: No default session found!');
        return;
      }
    } else {
      console.log('❌ PROBLEM: Cannot connect to WAHA API!');
      return;
    }
    
    // 2. Test different phone number formats
    console.log('\n2️⃣ Testing different phone number formats...');
    const phoneFormats = [
      '+201066544750@c.us',
      '201066544750@c.us', 
      '+201066544750@s.whatsapp.net',
      '201066544750@s.whatsapp.net'
    ];
    
    console.log('📱 Testing formats for obaid:');
    
    for (const format of phoneFormats) {
      console.log(`\n   Testing: ${format}`);
      
      try {
        const testMessage = {
          session: 'default',
          chatId: format,
          text: `Format test: ${format} - ${new Date().toLocaleTimeString()}`
        };
        
        const response = await fetch('http://localhost:3005/api/sendText', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-Api-Key': '992659f827564646ba3ab95ead50adc9'
          },
          body: JSON.stringify(testMessage)
        });
        
        if (response.ok) {
          const result = await response.json();
          console.log(`   ✅ API Success: ID ${result.key?.id}, Status: ${result.status}`);
          
          // Wait 2 seconds and check delivery status if available
          await new Promise(resolve => setTimeout(resolve, 2000));
          
        } else {
          const error = await response.text();
          console.log(`   ❌ API Failed: ${response.status} - ${error}`);
        }
        
      } catch (error) {
        console.log(`   ❌ Error: ${error.message}`);
      }
    }
    
    // 3. Try sending to the connected WhatsApp number instead
    console.log('\n3️⃣ Testing send to connected WhatsApp number...');
    
    const sessionResponse2 = await fetch('http://localhost:3005/api/sessions', {
      headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
    });
    
    if (sessionResponse2.ok) {
      const sessions = await sessionResponse2.json();
      const defaultSession = sessions.find(s => s.name === 'default');
      
      if (defaultSession?.me?.id) {
        console.log(`📱 Sending test to connected number: ${defaultSession.me.id}`);
        
        try {
          const selfTestMessage = {
            session: 'default',
            chatId: defaultSession.me.id,
            text: `🧪 SELF TEST MESSAGE
            
This is a test message sent to the connected WhatsApp account to verify message delivery is working.

Time: ${new Date().toLocaleString()}
From: Clinera Reminder System`
          };
          
          const response = await fetch('http://localhost:3005/api/sendText', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-Api-Key': '992659f827564646ba3ab95ead50adc9'
            },
            body: JSON.stringify(selfTestMessage)
          });
          
          if (response.ok) {
            const result = await response.json();
            console.log(`   ✅ Self-test sent successfully!`);
            console.log(`   📱 Check the WhatsApp account connected to WAHA`);
            console.log(`   📞 Number: ${defaultSession.me.id}`);
          } else {
            console.log(`   ❌ Self-test failed: ${response.status}`);
          }
          
        } catch (error) {
          console.log(`   ❌ Self-test error: ${error.message}`);
        }
      }
    }
    
    // 4. Check recent message logs in detail
    console.log('\n4️⃣ Checking recent message logs...');
    const { PrismaClient } = require('@prisma/client');
    const prisma = new PrismaClient();
    
    try {
      const recentMessages = await prisma.messageLog.findMany({
        where: { 
          direction: 'outgoing',
          createdAt: { gte: new Date(Date.now() - 30 * 60 * 1000) } // last 30 minutes
        },
        orderBy: { createdAt: 'desc' },
        take: 10,
        include: {
          appointment: {
            include: { lead: true }
          }
        }
      });
      
      console.log(`📊 Recent messages (last 30 min): ${recentMessages.length}`);
      
      recentMessages.forEach((msg, i) => {
        console.log(`\n   ${i + 1}. To: ${msg.phone}`);
        console.log(`      Patient: ${msg.appointment?.lead?.name || 'Unknown'}`);
        console.log(`      Status: ${msg.status}`);
        console.log(`      WAHA ID: ${msg.wahaMessageId || 'None'}`);
        console.log(`      Sent: ${msg.sentAt}`);
        console.log(`      Delivered: ${msg.deliveredAt || 'No'}`);
        console.log(`      Read: ${msg.readAt || 'No'}`);
      });
      
      await prisma.$disconnect();
      
    } catch (error) {
      console.log(`❌ Database check failed: ${error.message}`);
    }
    
    // 5. Check WhatsApp Web status
    console.log('\n5️⃣ Checking if WhatsApp Web is properly connected...');
    
    try {
      const statusResponse = await fetch('http://localhost:3005/api/default/status', {
        headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
      });
      
      if (statusResponse.ok) {
        const status = await statusResponse.json();
        console.log('📱 WhatsApp Status:', status);
      } else {
        console.log('⚠️ Could not get WhatsApp status');
      }
    } catch (error) {
      console.log('⚠️ Status check failed:', error.message);
    }
    
    // 6. Recommendations
    console.log('\n🔧 TROUBLESHOOTING RECOMMENDATIONS:');
    console.log('1. Check if WhatsApp Web is still connected in your browser');
    console.log('2. Verify the phone number +201066544750 is correct');
    console.log('3. Check if WhatsApp is blocking messages from this number');
    console.log('4. Try restarting WAHA container if needed');
    console.log('5. Check spam/blocked messages in WhatsApp');
    
    console.log('\n📱 NEXT STEPS:');
    console.log('1. Check the connected WhatsApp account for any test messages');
    console.log('2. Verify obaid\'s WhatsApp number is active and correct');
    console.log('3. Try sending from WhatsApp Web manually first');
    
  } catch (error) {
    console.error('❌ Debug failed:', error);
  }
}

debugDelivery().catch(console.error);