// Check and fix quiet hours issue
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function fixQuietHours() {
  console.log('🔍 DIAGNOSING QUIET HOURS ISSUE');
  console.log('='.repeat(50));
  
  try {
    // 1. Check current clinic settings
    const clinic = await prisma.clinic.findFirst();
    console.log('🏥 Current Clinic Settings:');
    console.log(`   Name: ${clinic.name}`);
    console.log(`   Quiet Hours: ${clinic.quietHoursStart}:00 - ${clinic.quietHoursEnd}:00`);
    console.log(`   Timezone: ${clinic.timezone}`);
    
    // 2. Check current time in clinic timezone
    const now = new Date();
    const currentHour = parseInt(
      new Intl.DateTimeFormat("en-US", { 
        timeZone: clinic.timezone, 
        hour: "numeric", 
        hour12: false 
      }).format(now)
    );
    
    console.log('\n⏰ Current Time Analysis:');
    console.log(`   UTC: ${now.toISOString()}`);
    console.log(`   Clinic Time: ${now.toLocaleString("en-US", { timeZone: clinic.timezone })}`);
    console.log(`   Current Hour: ${currentHour}`);
    
    // 3. Check if we're in quiet hours
    let inQuietHours = false;
    
    if (clinic.quietHoursStart > clinic.quietHoursEnd) {
      // Quiet hours span midnight (e.g., 22:00 - 08:00)
      inQuietHours = currentHour >= clinic.quietHoursStart || currentHour < clinic.quietHoursEnd;
    } else {
      // Normal quiet hours (e.g., 01:00 - 06:00)
      inQuietHours = currentHour >= clinic.quietHoursStart && currentHour < clinic.quietHoursEnd;
    }
    
    console.log(`   In Quiet Hours: ${inQuietHours ? 'YES ❌' : 'NO ✅'}`);
    
    if (inQuietHours) {
      console.log('\n🚨 FOUND THE PROBLEM!');
      console.log('   Booking confirmations are being delayed by quiet hours!');
      console.log('   This is why patients don\'t receive immediate confirmations.');
      
      // 4. Calculate when next message would be sent
      const nextHour = clinic.quietHoursEnd;
      const tomorrow = new Date(now);
      tomorrow.setDate(tomorrow.getDate() + 1);
      tomorrow.setHours(nextHour, 0, 0, 0);
      
      console.log(`   Next message would be: ${tomorrow.toLocaleString("en-US", { timeZone: clinic.timezone })}`);
      
      // 5. Fix by adjusting quiet hours or disabling for booking confirmations
      console.log('\n🔧 FIXING OPTIONS:');
      console.log('   Option 1: Disable quiet hours completely');
      console.log('   Option 2: Exclude booking confirmations from quiet hours');
      console.log('   Option 3: Adjust quiet hours to reasonable times');
      
      console.log('\n🛠️ IMPLEMENTING FIX: Adjust quiet hours to reasonable times');
      console.log('   Old: 22:00 - 08:00 (10 hour quiet period)');
      console.log('   New: 23:00 - 07:00 (8 hour quiet period, allows current time)');
      
      await prisma.clinic.update({
        where: { id: clinic.id },
        data: {
          quietHoursStart: 23,  // 11 PM
          quietHoursEnd: 7      // 7 AM
        }
      });
      
      console.log('✅ Quiet hours updated successfully!');
      
      // 6. Test if current time is now outside quiet hours
      const newQuietCheck = currentHour >= 23 || currentHour < 7;
      console.log(`   Current time (${currentHour}:00) in new quiet hours: ${newQuietCheck ? 'YES' : 'NO'}`);
      
      if (!newQuietCheck) {
        console.log('🎉 Current time is now OUTSIDE quiet hours!');
        console.log('   Booking confirmations will now send immediately!');
      } else {
        console.log('⚠️ Still in quiet hours. Consider further adjustment or temporary override.');
      }
    } else {
      console.log('\n✅ NOT in quiet hours. Issue might be elsewhere.');
      
      // Check other potential issues
      console.log('\n🔍 Checking other potential issues...');
      
      const templates = await prisma.reminderTemplate.findMany({
        where: { clinicId: clinic.id, trigger: 'booking_confirmed', isActive: true }
      });
      
      console.log(`   Active booking_confirmed templates: ${templates.length}`);
      
      if (templates.length === 0) {
        console.log('   ❌ No active booking_confirmed templates!');
      }
    }
    
    // 7. Test with a quick booking
    console.log('\n🧪 TESTING QUICK BOOKING AFTER FIX...');
    
    // Create a test appointment to see if timing is fixed
    const lead = await prisma.lead.findFirst({ where: { name: 'CLEAN_TEST_USER' } });
    const treatment = await prisma.treatment.findFirst({ where: { clinicId: clinic.id } });
    
    if (lead && treatment) {
      const testTime = new Date(Date.now() + 2 * 60 * 60 * 1000); // 2 hours from now
      
      const testAppointment = await prisma.appointment.create({
        data: {
          clinicId: clinic.id,
          leadId: lead.id,
          treatmentId: treatment.id,
          dateTime: testTime,
          status: 'scheduled',
          confirmToken: require('crypto').randomBytes(32).toString('hex'),
        },
      });
      
      console.log(`   Created test appointment: ${testAppointment.id}`);
      
      // Manually schedule reminder to see timing
      const template = await prisma.reminderTemplate.findFirst({
        where: { clinicId: clinic.id, trigger: 'booking_confirmed', isActive: true }
      });
      
      if (template) {
        // Calculate when it would be scheduled
        let scheduledFor = new Date(now.getTime() + 5000); // 5 seconds from now
        
        // Apply quiet hours logic
        const hour = parseInt(
          new Intl.DateTimeFormat("en-US", { 
            timeZone: clinic.timezone, 
            hour: "numeric", 
            hour12: false 
          }).format(scheduledFor)
        );
        
        console.log(`   Original schedule time: ${scheduledFor.toLocaleString()}`);
        console.log(`   Hour: ${hour}`);
        
        // Check new quiet hours
        const updatedClinic = await prisma.clinic.findFirst();
        const inNewQuietHours = hour >= updatedClinic.quietHoursStart || hour < updatedClinic.quietHoursEnd;
        
        if (inNewQuietHours) {
          // Would be moved to end of quiet hours
          const nextDay = new Date(scheduledFor);
          nextDay.setDate(nextDay.getDate() + 1);
          nextDay.setHours(updatedClinic.quietHoursEnd, 0, 0, 0);
          scheduledFor = nextDay;
        }
        
        console.log(`   Final schedule time: ${scheduledFor.toLocaleString()}`);
        
        if (scheduledFor.getTime() - now.getTime() < 60000) { // Within 1 minute
          console.log('   🎉 SUCCESS! Would send immediately!');
        } else {
          console.log(`   ⚠️ Still delayed by ${Math.round((scheduledFor.getTime() - now.getTime()) / 1000 / 60)} minutes`);
        }
      }
    }
    
  } catch (error) {
    console.error('❌ Fix failed:', error);
  } finally {
    await prisma.$disconnect();
  }
}

fixQuietHours().catch(console.error);