// Create a test appointment with immediate reminders
const { PrismaClient } = require('@prisma/client');
const crypto = require('crypto');
const prisma = new PrismaClient();

async function main() {
  console.log('🧪 Creating test appointment with immediate reminders...');
  
  // Get clinic and treatment
  const clinic = await prisma.clinic.findFirst();
  const treatment = await prisma.treatment.findFirst({ where: { clinicId: clinic.id } });
  const lead = await prisma.lead.findFirst({ where: { clinicId: clinic.id } });
  
  // Create appointment in 10 minutes
  const appointmentTime = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes from now
  
  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(`✅ Created appointment for ${appointmentTime.toLocaleString()}`);
  
  // Now create immediate reminders manually
  const templates = await prisma.reminderTemplate.findMany({
    where: { 
      clinicId: clinic.id,
      trigger: { in: ['booking_confirmed', '30_min_before'] }
    }
  });
  
  for (const template of templates) {
    let scheduledFor;
    
    if (template.trigger === 'booking_confirmed') {
      scheduledFor = new Date(); // Send immediately
    } else {
      scheduledFor = new Date(appointmentTime.getTime() + template.offsetMinutes * 60000);
    }
    
    await prisma.scheduledReminder.create({
      data: {
        appointmentId: appointment.id,
        templateId: template.id,
        scheduledFor: scheduledFor,
      },
    });
    
    console.log(`📅 Scheduled ${template.trigger} for ${scheduledFor.toLocaleString()}`);
  }
  
  // Check how many are due now
  const dueNow = await prisma.scheduledReminder.count({
    where: {
      status: 'pending',
      scheduledFor: { lte: new Date() }
    }
  });
  
  console.log(`⏰ Reminders due now: ${dueNow}`);
  
  await prisma.$disconnect();
}

main().catch(console.error);