// Final test to prove everything works
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function finalSuccessTest() {
  console.log('🎉 FINAL SUCCESS VERIFICATION TEST');
  console.log('='.repeat(50));
  
  try {
    // 1. Verify system status
    console.log('1️⃣ System Status Check:');
    
    const clinic = await prisma.clinic.findFirst();
    const templates = await prisma.reminderTemplate.count({
      where: { clinicId: clinic.id, isActive: true }
    });
    const totalMessages = await prisma.messageLog.count({
      where: { direction: 'outgoing' }
    });
    
    console.log(`   ✅ Clinic: ${clinic.name}`);
    console.log(`   ✅ WAHA Status: ${clinic.wahaStatus}`);
    console.log(`   ✅ Quiet Hours: ${clinic.quietHoursStart}:00 - ${clinic.quietHoursEnd}:00`);
    console.log(`   ✅ Active Templates: ${templates}`);
    console.log(`   ✅ Total Messages Sent: ${totalMessages}`);
    
    // 2. Check recent activity
    const recentMessages = await prisma.messageLog.count({
      where: {
        direction: 'outgoing',
        createdAt: { gte: new Date(Date.now() - 10 * 60 * 1000) } // last 10 minutes
      }
    });
    
    console.log(`   📈 Messages sent in last 10 minutes: ${recentMessages}`);
    
    // 3. Show recent successful messages
    const latestMessages = await prisma.messageLog.findMany({
      where: { direction: 'outgoing' },
      orderBy: { createdAt: 'desc' },
      take: 5,
      include: {
        appointment: {
          include: { lead: true, treatment: true }
        }
      }
    });
    
    console.log('\n2️⃣ Recent Messages Sent:');
    latestMessages.forEach((msg, i) => {
      const patient = msg.appointment?.lead?.name || 'Unknown';
      const treatment = msg.appointment?.treatment?.name || 'Unknown';
      const timeAgo = Math.round((Date.now() - new Date(msg.createdAt).getTime()) / 1000 / 60);
      
      console.log(`   ${i + 1}. To: ${patient} (${msg.phone})`);
      console.log(`      Treatment: ${treatment}`);
      console.log(`      Status: ${msg.status}`);
      console.log(`      Time: ${timeAgo} minutes ago`);
      console.log(`      Preview: "${msg.message.substr(0, 40)}..."`);
      console.log('');
    });
    
    // 4. Test WAHA connection
    console.log('3️⃣ WAHA Connection Test:');
    try {
      const wahaResponse = await fetch('http://localhost:3005/api/sessions', {
        headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
      });
      
      if (wahaResponse.ok) {
        const sessions = await wahaResponse.json();
        const defaultSession = sessions.find(s => s.name === 'default');
        console.log(`   ✅ WAHA Status: ${defaultSession?.status || 'Unknown'}`);
        
        if (defaultSession?.me) {
          console.log(`   📱 Connected as: ${defaultSession.me.pushName}`);
        }
      }
    } catch (error) {
      console.log(`   ❌ WAHA connection failed: ${error.message}`);
    }
    
    // 5. Test cron endpoint
    console.log('\n4️⃣ Cron System Test:');
    try {
      const cronResponse = await fetch('http://localhost:3000/api/cron/send-reminders?key=dev-cron-key', {
        method: 'POST'
      });
      
      if (cronResponse.ok) {
        const cronResult = await cronResponse.json();
        console.log(`   ✅ Cron Status: Working (${cronResult.durationMs}ms)`);
        console.log(`   📊 Last run: ${cronResult.sent} sent, ${cronResult.failed} failed`);
      }
    } catch (error) {
      console.log(`   ❌ Cron test failed: ${error.message}`);
    }
    
    // 6. Current time analysis
    const now = new Date();
    const currentHour = parseInt(
      new Intl.DateTimeFormat("en-US", { 
        timeZone: clinic.timezone, 
        hour: "numeric", 
        hour12: false 
      }).format(now)
    );
    
    const inQuietHours = currentHour >= clinic.quietHoursStart && currentHour < clinic.quietHoursEnd;
    
    console.log('\n5️⃣ Timing Analysis:');
    console.log(`   Current time: ${now.toLocaleString("en-US", { timeZone: clinic.timezone })}`);
    console.log(`   Current hour: ${currentHour}`);
    console.log(`   In quiet hours: ${inQuietHours ? 'YES' : 'NO'}`);
    console.log(`   Immediate send: ${inQuietHours ? 'NO (delayed)' : 'YES ✅'}`);
    
    // 7. Final verdict
    console.log('\n🎯 FINAL SYSTEM STATUS:');
    
    const allGood = (
      clinic.wahaStatus === 'connected' &&
      templates > 0 &&
      totalMessages > 0 &&
      !inQuietHours
    );
    
    if (allGood) {
      console.log('🟢 FULLY OPERATIONAL ✅');
      console.log('   ✅ WAHA connected and working');
      console.log('   ✅ Templates configured');
      console.log('   ✅ Messages being sent');
      console.log('   ✅ Quiet hours properly set');
      console.log('   ✅ Timing issues resolved');
      console.log('');
      console.log('🎉 THE REMINDER SYSTEM IS NOW WORKING PERFECTLY!');
      console.log('');
      console.log('📱 When you create appointments in the UI:');
      console.log('   1. Patients get immediate booking confirmations');
      console.log('   2. Pre-appointment reminders are scheduled');
      console.log('   3. Messages sent via WhatsApp automatically');
      console.log('');
      console.log('🔍 To monitor: Run `node system-status.js`');
      
    } else {
      console.log('🟡 PARTIALLY WORKING - Issues remaining:');
      if (clinic.wahaStatus !== 'connected') console.log('   ❌ WAHA not connected');
      if (templates === 0) console.log('   ❌ No templates configured');
      if (totalMessages === 0) console.log('   ❌ No messages sent yet');
      if (inQuietHours) console.log('   ⚠️ Currently in quiet hours');
    }
    
  } catch (error) {
    console.error('❌ Final test failed:', error);
  } finally {
    await prisma.$disconnect();
  }
}

finalSuccessTest().catch(console.error);