// Real-time monitoring of appointments and reminders
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function monitor() {
  console.log('🔍 REAL-TIME APPOINTMENT & REMINDER MONITOR');
  console.log('='.repeat(60));
  
  let lastAppointmentCount = 0;
  let lastReminderCount = 0;
  
  setInterval(async () => {
    try {
      // Count current appointments
      const appointmentCount = await prisma.appointment.count();
      const reminderCount = await prisma.scheduledReminder.count();
      const pendingReminders = await prisma.scheduledReminder.count({
        where: { status: 'pending' }
      });
      const sentMessages = await prisma.messageLog.count({
        where: { direction: 'outgoing' }
      });
      
      // Check if new appointments were added
      if (appointmentCount > lastAppointmentCount) {
        console.log(`\n🆕 NEW APPOINTMENT DETECTED! Total: ${appointmentCount}`);
        
        // Get the latest appointment
        const latest = await prisma.appointment.findFirst({
          orderBy: { createdAt: 'desc' },
          include: {
            lead: true,
            treatment: true,
            scheduledReminders: {
              include: { template: true }
            }
          }
        });
        
        if (latest) {
          console.log(`   Patient: ${latest.lead.name} (${latest.lead.phone})`);
          console.log(`   Treatment: ${latest.treatment.name}`);
          console.log(`   DateTime: ${latest.dateTime}`);
          console.log(`   Confirm Token: ${latest.confirmToken ? 'YES' : 'NO'}`);
          console.log(`   Reminders Scheduled: ${latest.scheduledReminders.length}`);
          
          if (latest.scheduledReminders.length === 0) {
            console.log('   ❌ ERROR: No reminders were scheduled for this appointment!');
          } else {
            console.log('   ✅ Reminders found:');
            latest.scheduledReminders.forEach(r => {
              console.log(`      - ${r.template.trigger} (${r.status}) at ${r.scheduledFor}`);
            });
          }
        }
      }
      
      // Check if new reminders were added
      if (reminderCount > lastReminderCount) {
        console.log(`\n📅 REMINDERS UPDATED: ${reminderCount} total, ${pendingReminders} pending`);
      }
      
      // Status summary
      if (appointmentCount !== lastAppointmentCount || reminderCount !== lastReminderCount) {
        console.log(`📊 Status: ${appointmentCount} appointments, ${reminderCount} reminders, ${sentMessages} messages sent`);
      }
      
      lastAppointmentCount = appointmentCount;
      lastReminderCount = reminderCount;
      
      // Test cron every 30 seconds
      const now = new Date();
      if (now.getSeconds() % 30 === 0) {
        try {
          const response = await fetch('http://localhost:3000/api/cron/send-reminders?key=dev-cron-key', {
            method: 'POST'
          });
          
          if (response.ok) {
            const result = await response.json();
            if (result.sent > 0 || result.failed > 0) {
              console.log(`⏰ Cron: sent=${result.sent}, failed=${result.failed}, skipped=${result.skipped}`);
            }
          }
        } catch (e) {
          // Ignore cron errors during monitoring
        }
      }
      
    } catch (error) {
      console.error('❌ Monitor error:', error.message);
    }
  }, 2000); // Check every 2 seconds
}

console.log('Starting monitor... Create appointments in the UI to see real-time tracking.');
console.log('Press Ctrl+C to stop.\n');

monitor().catch(console.error);