// Final comprehensive test of the reminder system
const { PrismaClient } = require('@prisma/client');
const crypto = require('crypto');
const prisma = new PrismaClient();

async function main() {
  console.log('🧪 FINAL COMPREHENSIVE REMINDER SYSTEM TEST');
  console.log('='.repeat(50));
  
  try {
    // 1. Ensure clinic exists
    let clinic = await prisma.clinic.findFirst();
    if (!clinic) {
      console.log('❌ No clinic found - please run setup first');
      return;
    }
    console.log(`✅ Clinic: ${clinic.name}`);
    
    // 2. Ensure active templates exist
    const templates = await prisma.reminderTemplate.count({
      where: { clinicId: clinic.id, isActive: true }
    });
    console.log(`✅ Active templates: ${templates}`);
    
    if (templates === 0) {
      console.log('❌ No active templates - system cannot work');
      return;
    }
    
    // 3. Check WAHA status
    console.log(`✅ WAHA Status: ${clinic.wahaStatus}`);
    
    // 4. Create test appointment that should trigger immediate reminder
    const treatment = await prisma.treatment.findFirst({ 
      where: { clinicId: clinic.id } 
    });
    const lead = await prisma.lead.findFirst({ 
      where: { clinicId: clinic.id } 
    });
    
    if (!treatment || !lead) {
      console.log('❌ No treatment or lead found');
      return;
    }
    
    // Create appointment 30 minutes from now
    const appointmentTime = new Date(Date.now() + 30 * 60 * 1000);
    
    console.log('\n📝 Creating test appointment...');
    const appointment = await prisma.appointment.create({
      data: {
        clinicId: clinic.id,
        leadId: lead.id,
        treatmentId: treatment.id,
        dateTime: appointmentTime,
        status: 'scheduled',
        confirmToken: crypto.randomBytes(32).toString('hex'),
      },
    });
    console.log(`✅ Appointment created for ${appointmentTime.toLocaleString()}`);
    
    // 5. Manually trigger reminder scheduling (simulating what the API does)
    console.log('\n📅 Scheduling reminders...');
    
    const reminderTemplates = await prisma.reminderTemplate.findMany({
      where: { 
        clinicId: clinic.id,
        isActive: true,
        trigger: 'booking_confirmed' // This should send immediately
      }
    });
    
    for (const template of reminderTemplates) {
      await prisma.scheduledReminder.create({
        data: {
          appointmentId: appointment.id,
          templateId: template.id,
          scheduledFor: new Date(), // Due immediately
        },
      });
    }
    
    console.log(`✅ ${reminderTemplates.length} reminders scheduled`);
    
    // 6. Check how many reminders are due now
    const dueReminders = await prisma.scheduledReminder.count({
      where: {
        status: 'pending',
        scheduledFor: { lte: new Date() }
      }
    });
    console.log(`⏰ Reminders due now: ${dueReminders}`);
    
    // 7. Test the cron endpoint
    console.log('\n⏰ Testing cron endpoint...');
    
    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();
        console.log('✅ Cron Response:', JSON.stringify(result, null, 2));
        
        if (result.sent > 0) {
          console.log('\n🎉 SUCCESS! Reminders are being sent!');
        } else if (result.failed > 0) {
          console.log('\n⚠️ Reminders failed to send - check WAHA connection');
        } else {
          console.log('\n⚠️ No reminders processed - check timing or templates');
        }
      } else {
        console.log(`❌ Cron failed: ${response.status}`);
      }
    } catch (error) {
      console.log(`❌ Error calling cron: ${error.message}`);
      console.log('   Make sure Clinera app is running on port 3000');
    }
    
    // 8. Final verification
    console.log('\n📊 FINAL STATUS:');
    console.log(`   Clinics: ${await prisma.clinic.count()}`);
    console.log(`   Templates: ${await prisma.reminderTemplate.count({ where: { isActive: true } })}`);
    console.log(`   Appointments: ${await prisma.appointment.count()}`);
    console.log(`   Scheduled Reminders: ${await prisma.scheduledReminder.count()}`);
    console.log(`   Sent Messages: ${await prisma.messageLog.count()}`);
    
  } catch (error) {
    console.error('❌ Test failed:', error);
  } finally {
    await prisma.$disconnect();
  }
}

main().catch(console.error);