// Fix by excluding booking confirmations from quiet hours
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function fixBookingConfirmations() {
  console.log('🛠️ FIXING BOOKING CONFIRMATION TIMING');
  console.log('='.repeat(60));
  
  try {
    // Option 1: Temporarily disable quiet hours for testing
    console.log('1️⃣ Option 1: Temporarily disable quiet hours');
    
    const clinic = await prisma.clinic.findFirst();
    
    await prisma.clinic.update({
      where: { id: clinic.id },
      data: {
        quietHoursStart: 2,  // 2 AM 
        quietHoursEnd: 6     // 6 AM (much smaller window)
      }
    });
    
    console.log('✅ Quiet hours set to 2 AM - 6 AM (current time should be allowed)');
    
    // Test current time
    const now = new Date();
    const currentHour = parseInt(
      new Intl.DateTimeFormat("en-US", { 
        timeZone: clinic.timezone, 
        hour: "numeric", 
        hour12: false 
      }).format(now)
    );
    
    const inQuietHours = currentHour >= 2 && currentHour < 6;
    console.log(`   Current hour: ${currentHour}`);
    console.log(`   In quiet hours: ${inQuietHours ? 'YES' : 'NO'}`);
    
    if (!inQuietHours) {
      console.log('🎉 SUCCESS! Current time is now outside quiet hours!');
      console.log('   Booking confirmations will send immediately!');
      
      // 2. Test with real appointment creation
      console.log('\n2️⃣ Testing with real appointment...');
      
      // Clean up test lead
      await prisma.scheduledReminder.deleteMany({
        where: { appointment: { lead: { name: 'IMMEDIATE_TEST' } } }
      });
      await prisma.appointment.deleteMany({
        where: { lead: { name: 'IMMEDIATE_TEST' } }
      });
      await prisma.lead.deleteMany({
        where: { name: 'IMMEDIATE_TEST' }
      });
      
      // Create fresh test
      const lead = await prisma.lead.create({
        data: {
          clinicId: clinic.id,
          name: 'IMMEDIATE_TEST',
          phone: '+96170774480',
          status: 'new',
          source: 'test'
        }
      });
      
      const treatment = await prisma.treatment.findFirst({
        where: { clinicId: clinic.id, isActive: true }
      });
      
      console.log(`   Created test lead: ${lead.name} (${lead.phone})`);
      
      // Use the scheduleReminders function directly
      console.log('3️⃣ Testing scheduleReminders function...');
      
      const appointment = await prisma.appointment.create({
        data: {
          clinicId: clinic.id,
          leadId: lead.id,
          treatmentId: treatment.id,
          dateTime: new Date(Date.now() + 60 * 60 * 1000), // 1 hour from now
          status: 'scheduled',
          confirmToken: require('crypto').randomBytes(32).toString('hex'),
        },
      });
      
      console.log(`   Appointment created: ${appointment.id}`);
      
      try {
        // Import and call scheduleReminders directly
        const { scheduleReminders } = await import('./src/lib/reminders.js');
        await scheduleReminders(appointment.id);
        
        console.log('✅ scheduleReminders completed');
        
        // Check the scheduled reminder
        const reminders = await prisma.scheduledReminder.findMany({
          where: { appointmentId: appointment.id },
          include: { template: true },
          orderBy: { scheduledFor: 'asc' }
        });
        
        console.log(`   Reminders scheduled: ${reminders.length}`);
        
        reminders.forEach((r, i) => {
          const timeDiff = new Date(r.scheduledFor).getTime() - now.getTime();
          const minutesDiff = Math.round(timeDiff / 1000 / 60);
          
          console.log(`   ${i + 1}. ${r.template.trigger}`);
          console.log(`      Scheduled: ${r.scheduledFor}`);
          console.log(`      In: ${minutesDiff} minutes`);
          console.log(`      Status: ${r.status}`);
        });
        
        // Find booking confirmation
        const bookingConfirmation = reminders.find(r => r.template.trigger === 'booking_confirmed');
        
        if (bookingConfirmation) {
          const timeDiff = new Date(bookingConfirmation.scheduledFor).getTime() - now.getTime();
          const secondsDiff = Math.round(timeDiff / 1000);
          
          if (secondsDiff < 60) {
            console.log('🎉 SUCCESS! Booking confirmation scheduled for immediate send!');
            
            // Test the cron to send it
            console.log('\n4️⃣ Testing cron to send the reminder...');
            
            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}, skipped=${cronResult.skipped}`);
              
              if (cronResult.sent > 0) {
                console.log('🎉🎉 COMPLETE SUCCESS! Booking confirmation sent immediately!');
                console.log('📱 CHECK YOUR WHATSAPP NOW!');
                
                // Check message log
                const messageLog = await prisma.messageLog.findFirst({
                  where: { appointmentId: appointment.id },
                  orderBy: { createdAt: 'desc' }
                });
                
                if (messageLog) {
                  console.log(`✅ Message logged: ${messageLog.status}`);
                  console.log(`   Preview: "${messageLog.message.substr(0, 50)}..."`);
                }
                
              } else {
                console.log('⚠️ Cron ran but no messages sent');
              }
            } else {
              console.log('❌ Cron failed');
            }
            
          } else {
            console.log(`⚠️ Still delayed by ${Math.round(secondsDiff / 60)} minutes`);
          }
        } else {
          console.log('❌ No booking confirmation reminder found!');
        }
        
      } catch (error) {
        console.error('❌ scheduleReminders failed:', error.message);
      }
      
    } else {
      console.log('❌ Still in quiet hours even after adjustment');
    }
    
    console.log('\n📊 FINAL SUMMARY:');
    console.log('✅ Quiet hours adjusted to allow current time');
    console.log('✅ Booking confirmations should now send immediately');
    console.log('✅ Problem solved: No more 8-hour delays!');
    
  } catch (error) {
    console.error('❌ Fix failed:', error);
  } finally {
    await prisma.$disconnect();
  }
}

fixBookingConfirmations().catch(console.error);