// Test the reminder system by calling the cron endpoint
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function main() {
  console.log('🧪 Testing reminder system...');
  
  // 1. Check what appointments exist
  const appointments = await prisma.appointment.findMany({
    where: {
      status: { in: ['scheduled', 'confirmed'] },
    },
    include: { lead: true, treatment: true },
    orderBy: { dateTime: 'desc' },
    take: 3
  });
  
  console.log(`📋 Found ${appointments.length} appointments:`);
  appointments.forEach(apt => {
    console.log(`   ${apt.lead.name} - ${apt.treatment.name} at ${apt.dateTime}`);
  });
  
  // 2. Check pending reminders
  const pendingReminders = await prisma.scheduledReminder.findMany({
    where: { status: 'pending' },
    include: {
      appointment: {
        include: { lead: true, treatment: true }
      },
      template: true
    },
    take: 5
  });
  
  console.log(`\n⏳ Found ${pendingReminders.length} pending reminders:`);
  pendingReminders.forEach(reminder => {
    const apt = reminder.appointment;
    console.log(`   ${reminder.template.trigger} for ${apt.lead.name} at ${reminder.scheduledFor}`);
  });
  
  // 3. Check clinic WAHA status  
  const clinic = await prisma.clinic.findFirst();
  console.log(`\n📱 WAHA Status: ${clinic.wahaStatus}`);
  
  // 4. Call the cron endpoint to process any due reminders
  console.log('\n⏰ Calling cron endpoint to process reminders...');
  
  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 result:', result);
    } else {
      console.log('❌ Cron failed:', response.status, await response.text());
    }
  } catch (error) {
    console.log('❌ Error calling cron:', error.message);
  }
  
  await prisma.$disconnect();
}

main().catch(console.error);