// Send to the ACTUAL connected WhatsApp number
async function sendToRealNumber() {
  console.log('🔍 SENDING TO ACTUAL CONNECTED WHATSAPP NUMBER');
  console.log('='.repeat(60));
  
  try {
    // 1. Get the actual connected number from WAHA
    console.log('1️⃣ Getting actual connected WhatsApp number...');
    
    const sessionResponse = await fetch('http://localhost:3005/api/sessions', {
      headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
    });
    
    if (!sessionResponse.ok) {
      console.log('❌ Cannot get WAHA session info');
      return;
    }
    
    const sessions = await sessionResponse.json();
    const defaultSession = sessions.find(s => s.name === 'default');
    
    if (!defaultSession) {
      console.log('❌ No default session found');
      return;
    }
    
    const connectedNumber = defaultSession.me?.id;
    const connectedName = defaultSession.me?.pushName;
    
    console.log(`✅ Found connected WhatsApp:`);
    console.log(`   Name: ${connectedName}`);
    console.log(`   Number: ${connectedNumber}`);
    console.log(`   Status: ${defaultSession.status}`);
    
    if (!connectedNumber) {
      console.log('❌ No connected phone number found');
      return;
    }
    
    // 2. Send test message to the ACTUAL connected number
    console.log('\n2️⃣ Sending test message to YOUR connected WhatsApp...');
    
    const testMessage = {
      session: 'default',
      chatId: connectedNumber,
      text: `🎉 SUCCESS! CLINERA SYSTEM IS WORKING!

Hi ${connectedName}!

This message proves the Clinera reminder system is fully operational and can send messages to your actual WhatsApp number.

✅ WAHA Connection: Working
✅ Message Delivery: Success  
✅ Connected Number: ${connectedNumber}
✅ System Status: Fully Operational

The issue was we were sending to +201066544750 but your actual WhatsApp is ${connectedNumber}.

Time: ${new Date().toLocaleString()}

🎯 THE REMINDER SYSTEM IS NOW WORKING! 🎯`
    };
    
    const sendResponse = await fetch('http://localhost:3005/api/sendText', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Api-Key': '992659f827564646ba3ab95ead50adc9'
      },
      body: JSON.stringify(testMessage)
    });
    
    if (sendResponse.ok) {
      const result = await sendResponse.json();
      console.log('🎉 MESSAGE SENT SUCCESSFULLY TO YOUR ACTUAL WHATSAPP!');
      console.log(`   Message ID: ${result.key?.id}`);
      console.log(`   Status: ${result.status}`);
      console.log(`   Timestamp: ${result.messageTimestamp}`);
      
      // 3. Update database with correct number
      console.log('\n3️⃣ Updating database with correct WhatsApp number...');
      
      const { PrismaClient } = require('@prisma/client');
      const prisma = new PrismaClient();
      
      try {
        // Extract just the phone number without @c.us
        const cleanNumber = connectedNumber.replace('@c.us', '').replace('@s.whatsapp.net', '');
        const formattedNumber = '+' + cleanNumber;
        
        console.log(`   Updating obaid's number from +201066544750 to ${formattedNumber}`);
        
        // Update or create lead with correct number
        const clinic = await prisma.clinic.findFirst();
        
        let obaidLead = await prisma.lead.findFirst({
          where: { 
            OR: [
              { name: { contains: 'obaidalah' } },
              { name: { contains: 'obaid' } }
            ]
          }
        });
        
        if (obaidLead) {
          // Update existing lead
          obaidLead = await prisma.lead.update({
            where: { id: obaidLead.id },
            data: { phone: formattedNumber }
          });
          console.log(`   ✅ Updated lead: ${obaidLead.name} → ${formattedNumber}`);
        } else {
          // Create new lead  
          obaidLead = await prisma.lead.create({
            data: {
              clinicId: clinic.id,
              name: connectedName || 'obaidalah saleh',
              phone: formattedNumber,
              status: 'new',
              source: 'whatsapp'
            }
          });
          console.log(`   ✅ Created lead: ${obaidLead.name} (${formattedNumber})`);
        }
        
        // 4. Create appointment with correct number
        console.log('\n4️⃣ Creating appointment with CORRECT number...');
        
        const treatment = await prisma.treatment.findFirst({
          where: { clinicId: clinic.id, isActive: true }
        });
        
        const appointmentTime = new Date();
        appointmentTime.setDate(appointmentTime.getDate() + 1);
        appointmentTime.setHours(15, 0, 0, 0); // Tomorrow 3 PM
        
        const appointment = await prisma.appointment.create({
          data: {
            clinicId: clinic.id,
            leadId: obaidLead.id,
            treatmentId: treatment.id,
            dateTime: appointmentTime,
            status: 'scheduled',
            confirmToken: require('crypto').randomBytes(32).toString('hex'),
            notes: 'Test with correct WhatsApp number'
          },
        });
        
        console.log(`   ✅ Appointment created: ${appointment.id}`);
        console.log(`   📅 Date: ${appointmentTime.toLocaleString()}`);
        
        // 5. Schedule immediate booking confirmation
        const template = await prisma.reminderTemplate.findFirst({
          where: { 
            clinicId: clinic.id,
            trigger: 'booking_confirmed',
            isActive: true
          }
        });
        
        if (template) {
          await prisma.scheduledReminder.create({
            data: {
              appointmentId: appointment.id,
              templateId: template.id,
              scheduledFor: new Date(Date.now() + 5000), // 5 seconds
            },
          });
          
          console.log('   ✅ Booking confirmation scheduled');
          
          // Wait and send
          console.log('\n5️⃣ Sending booking confirmation...');
          await new Promise(resolve => setTimeout(resolve, 6000));
          
          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('   🎉 BOOKING CONFIRMATION SENT TO CORRECT NUMBER!');
            }
          }
        }
        
        await prisma.$disconnect();
        
      } catch (dbError) {
        console.error('❌ Database update failed:', dbError.message);
      }
      
      console.log('\n📱 CHECK YOUR WHATSAPP NOW!');
      console.log(`   Number: ${connectedNumber}`);
      console.log(`   You should receive:`);
      console.log(`   1. ✅ Test success message (immediate)`);
      console.log(`   2. ✅ Booking confirmation (within minutes)`);
      
    } else {
      const error = await sendResponse.text();
      console.log(`❌ Send failed: ${sendResponse.status} - ${error}`);
    }
    
  } catch (error) {
    console.error('❌ Failed:', error);
  }
}

sendToRealNumber().catch(console.error);