// Test all reminder types in the system
const { PrismaClient } = require('@prisma/client');
const crypto = require('crypto');
const prisma = new PrismaClient();

async function testAllReminders() {
  console.log('🧪 TESTING ALL REMINDER TYPES - COMPREHENSIVE TEST');
  console.log('='.repeat(60));
  
  try {
    // Get clinic, lead, and treatment
    const clinic = await prisma.clinic.findFirst();
    const obaidLead = await prisma.lead.findFirst({
      where: { phone: '+201066544750' }
    });
    const treatment = await prisma.treatment.findFirst({
      where: { clinicId: clinic.id, isActive: true }
    });
    
    if (!obaidLead) {
      console.log('❌ Obaid lead not found');
      return;
    }
    
    console.log('📋 Setup:');
    console.log(`   Clinic: ${clinic.name}`);
    console.log(`   Patient: ${obaidLead.name}`);
    console.log(`   Phone: ${obaidLead.phone}`);
    console.log(`   Treatment: ${treatment.name}`);
    
    // Get all active reminder templates
    const templates = await prisma.reminderTemplate.findMany({
      where: { clinicId: clinic.id, isActive: true },
      orderBy: { sortOrder: 'asc' }
    });
    
    console.log(`\n📅 Found ${templates.length} active reminder templates:`);
    templates.forEach((t, i) => {
      console.log(`   ${i + 1}. ${t.trigger} (offset: ${t.offsetMinutes} min)`);
    });
    
    // Create test appointments for different reminder scenarios
    const now = new Date();
    const testScenarios = [
      {
        name: 'Immediate Booking Confirmation',
        appointmentTime: new Date(now.getTime() + 24 * 60 * 60 * 1000), // Tomorrow
        remindersToTest: ['booking_confirmed'],
        scheduleTime: new Date(now.getTime() + 3000) // 3 seconds from now
      },
      {
        name: '1 Day Before Reminder',
        appointmentTime: new Date(now.getTime() + 25 * 60 * 60 * 1000), // Tomorrow + 1 hour
        remindersToTest: ['1_day_before'],
        scheduleTime: new Date(now.getTime() + 8000) // 8 seconds from now
      },
      {
        name: '2 Hours Before Reminder', 
        appointmentTime: new Date(now.getTime() + 2 * 60 * 60 * 1000 + 13000), // 2 hours + 13 seconds
        remindersToTest: ['2_hours_before'],
        scheduleTime: new Date(now.getTime() + 13000) // 13 seconds from now
      },
      {
        name: '30 Minutes Before Reminder',
        appointmentTime: new Date(now.getTime() + 30 * 60 * 1000 + 18000), // 30 min + 18 seconds
        remindersToTest: ['30_min_before'],
        scheduleTime: new Date(now.getTime() + 18000) // 18 seconds from now
      }
    ];
    
    console.log('\n🎯 Creating test appointments for all reminder types...');
    
    const createdAppointments = [];
    
    for (let i = 0; i < testScenarios.length; i++) {
      const scenario = testScenarios[i];
      
      console.log(`\n${i + 1}️⃣ Creating: ${scenario.name}`);
      console.log(`   Appointment time: ${scenario.appointmentTime.toLocaleString()}`);
      console.log(`   Test reminder: ${scenario.remindersToTest.join(', ')}`);
      
      // Create appointment
      const appointment = await prisma.appointment.create({
        data: {
          clinicId: clinic.id,
          leadId: obaidLead.id,
          treatmentId: treatment.id,
          dateTime: scenario.appointmentTime,
          status: 'scheduled',
          confirmToken: crypto.randomBytes(32).toString('hex'),
          notes: `Test for ${scenario.name} - ${scenario.remindersToTest.join(', ')}`
        },
      });
      
      console.log(`   ✅ Appointment created: ${appointment.id}`);
      
      // Schedule specific reminders for this test
      for (const reminderType of scenario.remindersToTest) {
        const template = templates.find(t => t.trigger === reminderType);
        
        if (template) {
          await prisma.scheduledReminder.create({
            data: {
              appointmentId: appointment.id,
              templateId: template.id,
              scheduledFor: scenario.scheduleTime,
            },
          });
          
          console.log(`   📅 Scheduled ${reminderType} for ${scenario.scheduleTime.toLocaleTimeString()}`);
        }
      }
      
      createdAppointments.push({ appointment, scenario });
    }
    
    console.log('\n⏰ REMINDER SCHEDULE:');
    console.log('   3 seconds: Booking confirmation');
    console.log('   8 seconds: 1 day before reminder');  
    console.log('   13 seconds: 2 hours before reminder');
    console.log('   18 seconds: 30 minutes before reminder');
    console.log('');
    console.log('📱 Watch your WhatsApp (+201066544750) for 4 messages over 20 seconds!');
    
    // Monitor and send reminders
    console.log('\n🚀 STARTING REMINDER SEQUENCE...');
    
    for (let countdown = 20; countdown > 0; countdown--) {
      process.stdout.write(`\r⏳ ${countdown}s remaining... `);
      
      // Check every 2 seconds for due reminders
      if (countdown % 2 === 0) {
        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();
            if (cronResult.sent > 0) {
              console.log(`\n📤 ${cronResult.sent} reminder(s) sent!`);
            }
          }
        } catch (cronError) {
          // Continue even if cron fails
        }
      }
      
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
    
    console.log('\n\n🏁 REMINDER SEQUENCE COMPLETE!');
    
    // Check final results
    console.log('\n📊 CHECKING RESULTS...');
    
    const sentReminders = await prisma.scheduledReminder.findMany({
      where: {
        appointmentId: { in: createdAppointments.map(ca => ca.appointment.id) },
        status: 'sent'
      },
      include: { template: true }
    });
    
    const sentMessages = await prisma.messageLog.findMany({
      where: {
        phone: '+201066544750',
        createdAt: { gte: new Date(now.getTime() - 60000) } // Last minute
      },
      orderBy: { createdAt: 'desc' }
    });
    
    console.log(`✅ Reminders sent: ${sentReminders.length}`);
    console.log(`✅ Messages logged: ${sentMessages.length}`);
    
    console.log('\n📱 MESSAGES SENT TO YOUR WHATSAPP:');
    sentReminders.forEach((r, i) => {
      console.log(`   ${i + 1}. ${r.template.trigger} (${r.status})`);
    });
    
    if (sentMessages.length > 0) {
      console.log('\n📝 Recent message previews:');
      sentMessages.slice(0, 4).forEach((msg, i) => {
        console.log(`   ${i + 1}. "${msg.message.substr(0, 50)}..." (${msg.status})`);
      });
    }
    
    // Test additional reminder types that need different triggers
    console.log('\n🧪 TESTING ADDITIONAL REMINDER TYPES...');
    
    // Test post-treatment reminders
    console.log('\n📋 Creating completed appointment for post-treatment reminders...');
    
    const completedAppointment = await prisma.appointment.create({
      data: {
        clinicId: clinic.id,
        leadId: obaidLead.id,
        treatmentId: treatment.id,
        dateTime: new Date(now.getTime() - 60 * 60 * 1000), // 1 hour ago
        status: 'completed',
        confirmToken: crypto.randomBytes(32).toString('hex'),
        completedAt: new Date(now.getTime() - 30 * 60 * 1000), // Completed 30 min ago
        notes: 'Test for post-treatment reminders'
      },
    });
    
    // Schedule post-treatment reminders
    const postTreatmentTemplates = templates.filter(t => 
      t.trigger.includes('post_treatment')
    );
    
    for (const template of postTreatmentTemplates) {
      await prisma.scheduledReminder.create({
        data: {
          appointmentId: completedAppointment.id,
          templateId: template.id,
          scheduledFor: new Date(now.getTime() + 25000), // 25 seconds from now
        },
      });
      
      console.log(`   📅 Scheduled ${template.trigger}`);
    }
    
    // Final countdown for post-treatment
    if (postTreatmentTemplates.length > 0) {
      console.log('\n⏰ Waiting for post-treatment reminders...');
      
      for (let i = 25; i > 0; i--) {
        process.stdout.write(`\r⏳ ${i}s until post-treatment reminders...`);
        
        if (i % 5 === 0) {
          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();
              if (cronResult.sent > 0) {
                console.log(`\n📤 ${cronResult.sent} post-treatment reminder(s) sent!`);
              }
            }
          } catch (e) {}
        }
        
        await new Promise(resolve => setTimeout(resolve, 1000));
      }
    }
    
    console.log('\n\n🎉 COMPREHENSIVE REMINDER TEST COMPLETE!');
    console.log('='.repeat(50));
    
    const finalMessageCount = await prisma.messageLog.count({
      where: {
        phone: '+201066544750',
        createdAt: { gte: now }
      }
    });
    
    console.log(`📊 Total messages sent to you: ${finalMessageCount}`);
    console.log('📱 Check your WhatsApp (+201066544750) for ALL reminder types!');
    console.log('');
    console.log('✅ Tested reminder types:');
    console.log('   - Booking confirmation (immediate)');
    console.log('   - 1 day before reminder');
    console.log('   - 2 hours before reminder');
    console.log('   - 30 minutes before reminder');
    console.log('   - Post-treatment reminders');
    console.log('');
    console.log('🎯 THE COMPLETE REMINDER SYSTEM IS WORKING!');
    
  } catch (error) {
    console.error('❌ Test failed:', error);
  } finally {
    await prisma.$disconnect();
  }
}

testAllReminders().catch(console.error);