// Send booking confirmation to obaid
const { PrismaClient } = require('@prisma/client');
const crypto = require('crypto');
const prisma = new PrismaClient();

async function sendToObaid() {
  console.log('📱 SENDING MESSAGE TO OBAID');
  console.log('='.repeat(40));
  
  try {
    // 1. Find obaid's lead
    console.log('1️⃣ Finding obaid...');
    const obaidLead = await prisma.lead.findFirst({
      where: { 
        OR: [
          { name: { contains: 'obaidalah' } },
          { name: { contains: 'obaid' } },
          { phone: '+201066544750' }
        ]
      }
    });
    
    if (!obaidLead) {
      console.log('❌ Obaid not found, creating new lead...');
      
      const clinic = await prisma.clinic.findFirst();
      const newLead = await prisma.lead.create({
        data: {
          clinicId: clinic.id,
          name: 'obaidalah saleh',
          phone: '+201066544750',
          status: 'new',
          source: 'test'
        }
      });
      
      console.log(`✅ Created new lead: ${newLead.name} (${newLead.phone})`);
      obaidLead = newLead;
    } else {
      console.log(`✅ Found obaid: ${obaidLead.name} (${obaidLead.phone})`);
    }
    
    // 2. Get clinic and treatment
    const clinic = await prisma.clinic.findFirst();
    const treatment = await prisma.treatment.findFirst({
      where: { clinicId: clinic.id, isActive: true }
    });
    
    console.log(`   Clinic: ${clinic.name}`);
    console.log(`   Treatment: ${treatment.name}`);
    
    // 3. Create appointment for tomorrow
    console.log('2️⃣ Creating appointment...');
    const appointmentTime = new Date();
    appointmentTime.setDate(appointmentTime.getDate() + 1); // Tomorrow
    appointmentTime.setHours(14, 30, 0, 0); // 2:30 PM
    
    const appointment = await prisma.appointment.create({
      data: {
        clinicId: clinic.id,
        leadId: obaidLead.id,
        treatmentId: treatment.id,
        dateTime: appointmentTime,
        status: 'scheduled',
        confirmToken: crypto.randomBytes(32).toString('hex'),
        notes: 'Test appointment for obaid - message sending test'
      },
    });
    
    console.log(`✅ Appointment created: ${appointment.id}`);
    console.log(`   DateTime: ${appointmentTime.toLocaleString()}`);
    
    // 4. Schedule booking confirmation (should send immediately)
    console.log('3️⃣ Scheduling booking confirmation...');
    
    const template = await prisma.reminderTemplate.findFirst({
      where: { 
        clinicId: clinic.id,
        trigger: 'booking_confirmed',
        isActive: true
      }
    });
    
    if (!template) {
      console.log('❌ No booking confirmation template found!');
      return;
    }
    
    // Create reminder for immediate send (outside quiet hours)
    const reminder = await prisma.scheduledReminder.create({
      data: {
        appointmentId: appointment.id,
        templateId: template.id,
        scheduledFor: new Date(Date.now() + 3000), // 3 seconds from now
      },
    });
    
    console.log(`✅ Reminder scheduled for immediate send`);
    
    // 5. Wait a moment then trigger cron
    console.log('4️⃣ Waiting 5 seconds then sending...');
    await new Promise(resolve => setTimeout(resolve, 5000));
    
    console.log('📤 Triggering message send...');
    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}`);
      
      if (cronResult.sent > 0) {
        console.log('🎉 SUCCESS! Message sent to obaid!');
        
        // Check message log
        await new Promise(resolve => setTimeout(resolve, 2000));
        
        const messageLog = await prisma.messageLog.findFirst({
          where: { 
            appointmentId: appointment.id,
            phone: obaidLead.phone
          }
        });
        
        if (messageLog) {
          console.log('\n📱 MESSAGE DETAILS:');
          console.log(`   To: ${obaidLead.name}`);
          console.log(`   Phone: ${obaidLead.phone}`);
          console.log(`   Status: ${messageLog.status}`);
          console.log(`   Sent at: ${messageLog.sentAt}`);
          console.log(`   Message preview:`);
          console.log(`   "${messageLog.message.substr(0, 100)}..."`);
          
          console.log('\n📲 OBAID SHOULD RECEIVE THIS MESSAGE ON WHATSAPP NOW!');
        }
      } else if (cronResult.failed > 0) {
        console.log('❌ Message failed to send!');
      } else {
        console.log('⚠️ No messages were processed');
      }
    } else {
      console.log('❌ Cron endpoint failed');
    }
    
    // 6. Also schedule other reminders
    console.log('\n5️⃣ Scheduling additional reminders...');
    
    const otherTemplates = await prisma.reminderTemplate.findMany({
      where: { 
        clinicId: clinic.id,
        isActive: true,
        trigger: { not: 'booking_confirmed' }
      }
    });
    
    for (const t of otherTemplates) {
      let scheduledTime;
      
      if (t.trigger === '1_day_before') {
        // Schedule for tomorrow at 9 AM (1 day before 2:30 PM appointment)
        scheduledTime = new Date(appointmentTime);
        scheduledTime.setDate(scheduledTime.getDate() - 1);
        scheduledTime.setHours(9, 0, 0, 0);
      } else if (t.trigger === '2_hours_before') {
        // Schedule for 12:30 PM tomorrow (2 hours before 2:30 PM)
        scheduledTime = new Date(appointmentTime);
        scheduledTime.setHours(12, 30, 0, 0);
      } else {
        // Use template offset
        scheduledTime = new Date(appointmentTime.getTime() + t.offsetMinutes * 60000);
      }
      
      await prisma.scheduledReminder.create({
        data: {
          appointmentId: appointment.id,
          templateId: t.id,
          scheduledFor: scheduledTime,
        },
      });
      
      console.log(`   📅 ${t.trigger} scheduled for ${scheduledTime.toLocaleString()}`);
    }
    
    console.log('\n🎯 SUMMARY FOR OBAID:');
    console.log(`   📱 Phone: ${obaidLead.phone}`);
    console.log(`   📅 Appointment: ${appointmentTime.toLocaleString()}`);
    console.log(`   💊 Treatment: ${treatment.name}`);
    console.log(`   📨 Immediate confirmation: SENT ✅`);
    console.log(`   ⏰ Future reminders: SCHEDULED ✅`);
    
    console.log('\n📲 OBAID - CHECK YOUR WHATSAPP FOR THE BOOKING CONFIRMATION!');
    
  } catch (error) {
    console.error('❌ Failed to send to obaid:', error);
  } finally {
    await prisma.$disconnect();
  }
}

sendToObaid().catch(console.error);