// Debug what happens when appointments are created via UI
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function debugUIWorkflow() {
  console.log('🔍 DEBUGGING REAL UI APPOINTMENT WORKFLOW');
  console.log('='.repeat(60));
  
  // 1. Monitor database changes in real-time
  console.log('👀 Monitoring database for changes...');
  console.log('📝 Create an appointment in the UI now and watch this log');
  console.log('-'.repeat(60));
  
  let lastAppointmentCount = 0;
  let lastReminderCount = 0;
  let lastMessageCount = 0;
  let monitoringCount = 0;
  
  const monitor = setInterval(async () => {
    monitoringCount++;
    
    try {
      const currentAppointmentCount = await prisma.appointment.count();
      const currentReminderCount = await prisma.scheduledReminder.count();
      const currentMessageCount = await prisma.messageLog.count();
      
      // Check for new appointments
      if (currentAppointmentCount > lastAppointmentCount) {
        console.log(`\n🆕 NEW APPOINTMENT DETECTED! (#${currentAppointmentCount})`);
        
        // Get the newest appointment with full details
        const newest = await prisma.appointment.findFirst({
          orderBy: { createdAt: 'desc' },
          include: {
            lead: true,
            treatment: true,
            clinic: true,
            scheduledReminders: {
              include: { template: true },
              orderBy: { scheduledFor: 'asc' }
            }
          }
        });
        
        if (newest) {
          console.log(`📋 Details:`);
          console.log(`   Patient: ${newest.lead.name} (${newest.lead.phone})`);
          console.log(`   Treatment: ${newest.treatment.name}`);
          console.log(`   DateTime: ${newest.dateTime}`);
          console.log(`   Status: ${newest.status}`);
          console.log(`   Confirm Token: ${newest.confirmToken ? '✅ YES' : '❌ NO'}`);
          console.log(`   Created: ${newest.createdAt}`);
          console.log(`   Clinic WAHA: ${newest.clinic.wahaStatus}`);
          
          console.log(`\n📅 Reminders for this appointment: ${newest.scheduledReminders.length}`);
          if (newest.scheduledReminders.length === 0) {
            console.log(`   ❌ PROBLEM: NO REMINDERS SCHEDULED!`);
            
            // Check why no reminders
            console.log(`\n🔍 Investigating why no reminders...`);
            
            // Check if templates exist
            const templates = await prisma.reminderTemplate.findMany({
              where: { 
                clinicId: newest.clinicId,
                isActive: true
              }
            });
            
            console.log(`   📋 Active templates for this clinic: ${templates.length}`);
            if (templates.length === 0) {
              console.log(`   ❌ NO ACTIVE TEMPLATES FOUND!`);
              console.log(`   🔧 This is likely the main issue.`);
            } else {
              console.log(`   ✅ Templates available:`);
              templates.forEach(t => {
                console.log(`      - ${t.trigger} (${t.isActive ? 'active' : 'inactive'})`);
              });
              
              console.log(`\n   🔧 Templates exist but reminders not scheduled.`);
              console.log(`   📝 This suggests scheduleReminders() wasn't called or failed silently.`);
            }
            
          } else {
            console.log(`   ✅ Reminders found:`);
            newest.scheduledReminders.forEach(r => {
              console.log(`      - ${r.template.trigger} at ${r.scheduledFor} (${r.status})`);
            });
          }
          
          // Check if booking confirmation would be sent
          const dueNow = newest.scheduledReminders.filter(r => 
            r.status === 'pending' && new Date(r.scheduledFor) <= new Date()
          );
          
          console.log(`\n⏰ Reminders due now: ${dueNow.length}`);
          
          if (dueNow.length > 0) {
            console.log(`   🚀 Testing cron to send them...`);
            
            try {
              const cronResponse = await fetch('http://localhost:3000/api/cron/send-reminders?key=dev-cron-key', {
                method: 'POST'
              });
              
              if (cronResponse.ok) {
                const result = await cronResponse.json();
                console.log(`   📊 Cron result: sent=${result.sent}, failed=${result.failed}, skipped=${result.skipped}`);
                
                if (result.sent > 0) {
                  console.log(`   🎉 SUCCESS! Messages sent!`);
                } else if (result.failed > 0) {
                  console.log(`   ❌ Messages FAILED to send!`);
                } else if (result.skipped > 0) {
                  console.log(`   ⚠️ Messages were SKIPPED - check logic`);
                }
              } else {
                console.log(`   ❌ Cron endpoint failed: ${cronResponse.status}`);
              }
            } catch (e) {
              console.log(`   ❌ Cron call failed: ${e.message}`);
            }
          }
        }
      }
      
      // Check for new reminders
      if (currentReminderCount > lastReminderCount) {
        console.log(`📅 Reminders increased: ${lastReminderCount} → ${currentReminderCount}`);
      }
      
      // Check for new messages
      if (currentMessageCount > lastMessageCount) {
        console.log(`📨 Messages increased: ${lastMessageCount} → ${currentMessageCount}`);
        
        // Show latest message
        const latestMessage = await prisma.messageLog.findFirst({
          orderBy: { createdAt: 'desc' }
        });
        
        if (latestMessage) {
          console.log(`   Latest: ${latestMessage.direction} → ${latestMessage.phone}`);
          console.log(`   Status: ${latestMessage.status}`);
          console.log(`   Preview: "${latestMessage.message.substr(0, 50)}..."`);
        }
      }
      
      lastAppointmentCount = currentAppointmentCount;
      lastReminderCount = currentReminderCount;
      lastMessageCount = currentMessageCount;
      
      // Show periodic status
      if (monitoringCount % 10 === 0) {
        console.log(`\n⏱️ Status (${monitoringCount}s): ${currentAppointmentCount} appointments, ${currentReminderCount} reminders, ${currentMessageCount} messages`);
      }
      
    } catch (error) {
      console.error('❌ Monitor error:', error.message);
    }
  }, 1000); // Check every second
  
  // Stop after 5 minutes
  setTimeout(() => {
    clearInterval(monitor);
    console.log('\n🛑 Monitoring stopped. Create an appointment and run again if needed.');
    process.exit(0);
  }, 5 * 60 * 1000);
}

debugUIWorkflow().catch(console.error);