// Debug WAHA connection and message sending
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function debugWaha() {
  console.log('🔍 DEBUGGING WAHA CONNECTION...');
  console.log('='.repeat(50));
  
  try {
    // 1. Check WAHA status
    console.log('1️⃣ Testing WAHA API directly...');
    
    const wahaResponse = await fetch('http://localhost:3005/api/sessions', {
      headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
    });
    
    if (wahaResponse.ok) {
      const sessions = await wahaResponse.json();
      console.log('✅ WAHA API responding');
      console.log('   Sessions:', sessions.length);
      
      sessions.forEach(session => {
        console.log(`   - ${session.name}: ${session.status}`);
      });
    } else {
      console.log('❌ WAHA API failed:', wahaResponse.status);
      return;
    }
    
    // 2. Check clinic WAHA status in database
    console.log('\n2️⃣ Checking clinic WAHA status...');
    const clinic = await prisma.clinic.findFirst();
    console.log(`   Clinic: ${clinic.name}`);
    console.log(`   WAHA Status: ${clinic.wahaStatus}`);
    console.log(`   WAHA Session: ${clinic.wahaSessionId}`);
    console.log(`   Last Checked: ${clinic.wahaLastChecked}`);
    
    if (clinic.wahaStatus !== 'connected') {
      console.log('❌ Clinic WAHA status is not "connected"');
      
      // Update clinic status
      await prisma.clinic.update({
        where: { id: clinic.id },
        data: { 
          wahaStatus: 'connected',
          wahaSessionId: 'default',
          wahaLastChecked: new Date()
        }
      });
      console.log('✅ Fixed clinic WAHA status');
    }
    
    // 3. Test sending a message directly
    console.log('\n3️⃣ Testing direct message send...');
    
    const testMessage = {
      session: 'default',
      chatId: '+96170774480@c.us',
      text: 'Test message from Clinera debug script'
    };
    
    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('✅ Direct message send successful');
      console.log('   Result:', result);
    } else {
      console.log('❌ Direct message send failed:', sendResponse.status, await sendResponse.text());
    }
    
    // 4. Test using Clinera's sendMessage function
    console.log('\n4️⃣ Testing Clinera sendMessage function...');
    
    try {
      const { sendMessage } = await import('./src/lib/waha.js');
      const clineraResult = await sendMessage('+96170774480', 'Test via Clinera sendMessage function');
      console.log('✅ Clinera sendMessage successful');
      console.log('   Result:', clineraResult);
    } catch (error) {
      console.log('❌ Clinera sendMessage failed:', error.message);
    }
    
    // 5. Check message log
    console.log('\n5️⃣ Checking message log...');
    const messageCount = await prisma.messageLog.count();
    const recentMessages = await prisma.messageLog.findMany({
      take: 3,
      orderBy: { createdAt: 'desc' },
      select: {
        direction: true,
        phone: true,
        status: true,
        message: true,
        sentAt: true,
        createdAt: true
      }
    });
    
    console.log(`   Total messages: ${messageCount}`);
    if (recentMessages.length > 0) {
      console.log('   Recent messages:');
      recentMessages.forEach(msg => {
        console.log(`      ${msg.direction} → ${msg.phone}: "${msg.message.substr(0, 30)}..." (${msg.status})`);
      });
    } else {
      console.log('   No messages found');
    }
    
    console.log('\n📊 Summary:');
    console.log('   - WAHA API: Working ✅');
    console.log('   - Clinic Status: Fixed ✅');
    console.log(`   - Message Log: ${messageCount} entries`);
    
  } catch (error) {
    console.error('❌ Debug failed:', error);
  } finally {
    await prisma.$disconnect();
  }
}

debugWaha().catch(console.error);