// Monitor for obaid's new appointment in real-time
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function monitorObaidAppointment() {
  console.log('👀 MONITORING FOR OBAID\'S NEW APPOINTMENT');
  console.log('='.repeat(50));
  console.log('📱 Waiting for appointment creation...');
  console.log('   (Create your appointment in the UI now!)');
  console.log('');
  
  let lastAppointmentCount = await prisma.appointment.count();
  let lastReminderCount = await prisma.scheduledReminder.count();
  let lastMessageCount = await prisma.messageLog.count();
  let checkCount = 0;
  
  const monitor = setInterval(async () => {
    checkCount++;
    
    try {
      const currentAppointmentCount = await prisma.appointment.count();
      const currentReminderCount = await prisma.scheduledReminder.count();
      const currentMessageCount = await prisma.messageLog.count();
      
      // Check for new appointment
      if (currentAppointmentCount > lastAppointmentCount) {
        console.log('\n🆕 NEW APPOINTMENT DETECTED!');
        
        // Get the latest appointment
        const latestAppointment = await prisma.appointment.findFirst({
          where: {
            lead: { phone: '+201066544750' } // obaid's correct number
          },
          orderBy: { createdAt: 'desc' },
          include: {
            lead: true,
            treatment: true,
            scheduledReminders: {
              include: { template: true }
            }
          }
        });
        
        if (latestAppointment) {
          console.log(`📋 Appointment Details:`);
          console.log(`   ID: ${latestAppointment.id}`);
          console.log(`   Patient: ${latestAppointment.lead.name}`);
          console.log(`   Phone: ${latestAppointment.lead.phone}`);
          console.log(`   Treatment: ${latestAppointment.treatment.name}`);
          console.log(`   Date/Time: ${latestAppointment.dateTime}`);
          console.log(`   Status: ${latestAppointment.status}`);
          console.log(`   Created: ${latestAppointment.createdAt}`);
          console.log(`   Reminders: ${latestAppointment.scheduledReminders.length}`);
          
          if (latestAppointment.scheduledReminders.length > 0) {
            console.log('\n📅 Scheduled Reminders:');
            latestAppointment.scheduledReminders.forEach((r, i) => {
              console.log(`   ${i + 1}. ${r.template.trigger} - ${r.scheduledFor} (${r.status})`);
            });
            
            // Check for due reminders
            const dueNow = latestAppointment.scheduledReminders.filter(r => 
              r.status === 'pending' && new Date(r.scheduledFor) <= new Date()
            );
            
            if (dueNow.length > 0) {
              console.log(`\n⏰ ${dueNow.length} reminders due now - triggering cron...`);
              
              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 result: sent=${cronResult.sent}, failed=${cronResult.failed}`);
                
                if (cronResult.sent > 0) {
                  console.log('🎉 BOOKING CONFIRMATION SENT TO OBAID!');
                  console.log('📱 Check your WhatsApp (+201066544750)');
                }
              }
            }
          } else {
            console.log('❌ No reminders scheduled - something went wrong!');
          }
        }
      }
      
      // Check for new reminders
      if (currentReminderCount > lastReminderCount) {
        console.log(`📅 Reminders: ${lastReminderCount} → ${currentReminderCount}`);
      }
      
      // Check for new messages
      if (currentMessageCount > lastMessageCount) {
        console.log(`📨 Messages: ${lastMessageCount} → ${currentMessageCount}`);
        
        // Show latest message to obaid
        const latestMessage = await prisma.messageLog.findFirst({
          where: { phone: '+201066544750' },
          orderBy: { createdAt: 'desc' }
        });
        
        if (latestMessage) {
          console.log(`   Latest to obaid: ${latestMessage.status} - "${latestMessage.message.substr(0, 40)}..."`);
        }
      }
      
      // Update counters
      lastAppointmentCount = currentAppointmentCount;
      lastReminderCount = currentReminderCount;
      lastMessageCount = currentMessageCount;
      
      // Show status every 10 checks (20 seconds)
      if (checkCount % 10 === 0) {
        console.log(`⏱️ Monitoring... (${checkCount * 2}s) - ${currentAppointmentCount} appointments, ${currentMessageCount} messages`);
      }
      
    } catch (error) {
      console.error('❌ Monitor error:', error.message);
    }
  }, 2000); // Check every 2 seconds
  
  // Stop monitoring after 5 minutes
  setTimeout(() => {
    clearInterval(monitor);
    console.log('\n⏹️ Monitoring stopped.');
    console.log('If no appointment detected, create it in the Clinera UI.');
    prisma.$disconnect();
    process.exit(0);
  }, 5 * 60 * 1000);
}

console.log('🎯 OBAID - CREATE YOUR APPOINTMENT NOW!');
console.log('   This monitor will detect it and show the reminder flow.');
console.log('');

monitorObaidAppointment().catch(console.error);