// Send immediate text to obaid lead
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function sendTextToObaid() {
  console.log('📱 SENDING TEXT MESSAGE TO OBAID LEAD RIGHT NOW');
  console.log('='.repeat(50));
  
  try {
    // 1. Find obaid's lead
    console.log('1️⃣ Finding obaid lead...');
    
    const obaidLead = await prisma.lead.findFirst({
      where: { 
        OR: [
          { phone: '+96178701782' },
          { name: { contains: 'obaidalah' } },
          { name: { contains: 'Obaidalah' } }
        ]
      },
      include: { clinic: true }
    });
    
    if (!obaidLead) {
      console.log('❌ Obaid lead not found!');
      return;
    }
    
    console.log(`✅ Found obaid lead:`);
    console.log(`   Name: ${obaidLead.name}`);
    console.log(`   Phone: ${obaidLead.phone}`);
    console.log(`   Status: ${obaidLead.status}`);
    console.log(`   Clinic: ${obaidLead.clinic.name}`);
    
    // 2. Prepare message
    const currentTime = new Date();
    const message = `📱 DIRECT MESSAGE TO OBAID LEAD

Hi ${obaidLead.name}!

This is a direct text message sent to your lead profile in Clinera.

📋 Lead Details:
   Name: ${obaidLead.name}
   Phone: ${obaidLead.phone}
   Status: ${obaidLead.status}
   Source: ${obaidLead.source}
   Clinic: ${obaidLead.clinic.name}

⏰ Sent: ${currentTime.toLocaleString()}
🎯 Purpose: Testing direct messaging to leads
💡 This proves the lead → WhatsApp connection works!

✅ If you receive this message, the lead messaging system is fully operational!

From: Clinera Lead Messaging System`;

    console.log('\n2️⃣ Preparing message...');
    console.log(`   To: ${obaidLead.name}`);
    console.log(`   Phone: ${obaidLead.phone}`);
    console.log(`   Length: ${message.length} characters`);
    
    // 3. Convert phone number for WAHA
    const wahaPhoneNumber = obaidLead.phone.replace('+', '') + '@c.us';
    console.log(`   WAHA format: ${wahaPhoneNumber}`);
    
    // 4. Send via WAHA
    console.log('\n3️⃣ Sending via WAHA...');
    
    const wahaMessage = {
      session: 'default',
      chatId: wahaPhoneNumber,
      text: message
    };
    
    const sendResponse = await fetch('http://localhost:3005/api/sendText', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Api-Key': '992659f827564646ba3ab95ead50adc9'
      },
      body: JSON.stringify(wahaMessage)
    });
    
    if (sendResponse.ok) {
      const result = await sendResponse.json();
      console.log('✅ MESSAGE SENT SUCCESSFULLY!');
      console.log(`   Message ID: ${result.key?.id}`);
      console.log(`   Status: ${result.status}`);
      console.log(`   Timestamp: ${result.messageTimestamp}`);
      
      // 5. Log message in database
      console.log('\n4️⃣ Logging message in database...');
      
      const messageLog = await prisma.messageLog.create({
        data: {
          clinicId: obaidLead.clinicId,
          phone: obaidLead.phone,
          direction: 'outgoing',
          message: message,
          status: 'sent',
          wahaMessageId: result.key?.id || null,
          sentAt: new Date(),
        },
      });
      
      console.log(`✅ Message logged: ${messageLog.id}`);
      
      // 6. Update lead status
      await prisma.lead.update({
        where: { id: obaidLead.id },
        data: { 
          status: 'contacted',
          updatedAt: new Date()
        }
      });
      
      console.log('✅ Lead status updated to "contacted"');
      
      console.log('\n🎉 COMPLETE SUCCESS!');
      console.log('='.repeat(30));
      console.log(`📱 Text sent to: ${obaidLead.name}`);
      console.log(`📞 Phone: ${obaidLead.phone}`);
      console.log(`📨 Message ID: ${result.key?.id}`);
      console.log(`📊 Database logged: Yes`);
      console.log(`👤 Lead updated: contacted`);
      console.log('');
      console.log('📲 OBAID - CHECK YOUR WHATSAPP NOW!');
      console.log('   You should see the direct lead message!');
      
    } else {
      const error = await sendResponse.text();
      console.log(`❌ Message send failed:`);
      console.log(`   Status: ${sendResponse.status}`);
      console.log(`   Error: ${error}`);
    }
    
  } catch (error) {
    console.error('❌ Failed to send text:', error);
  } finally {
    await prisma.$disconnect();
  }
}

sendTextToObaid().catch(console.error);