// Test the complete workflow from appointment to message
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function testCompleteWorkflow() {
  console.log('🧪 TESTING COMPLETE APPOINTMENT → MESSAGE WORKFLOW');
  console.log('='.repeat(60));
  
  try {
    // 1. Clear old test data
    console.log('1️⃣ Cleaning up old test data...');
    await prisma.scheduledReminder.deleteMany({
      where: { 
        appointment: { 
          lead: { name: 'TEST USER' } 
        }
      }
    });
    await prisma.appointment.deleteMany({
      where: { lead: { name: 'TEST USER' } }
    });
    await prisma.lead.deleteMany({
      where: { name: 'TEST USER' }
    });
    
    // 2. Create test data
    const clinic = await prisma.clinic.findFirst();
    const treatment = await prisma.treatment.findFirst({ where: { clinicId: clinic.id } });
    
    console.log('2️⃣ Creating test lead...');
    const lead = await prisma.lead.create({
      data: {
        clinicId: clinic.id,
        name: 'TEST USER',
        phone: '+96170774480', // Your WhatsApp number
        status: 'new',
        source: 'test'
      }
    });
    console.log(`✅ Created lead: ${lead.name} (${lead.phone})`);
    
    // 3. Create appointment and manually trigger reminder system
    console.log('3️⃣ Creating appointment...');
    const appointmentTime = new Date(Date.now() + 5 * 60 * 1000); // 5 minutes from now
    
    const appointment = await prisma.appointment.create({
      data: {
        clinicId: clinic.id,
        leadId: lead.id,
        treatmentId: treatment.id,
        dateTime: appointmentTime,
        status: 'scheduled',
        confirmToken: require('crypto').randomBytes(32).toString('hex'),
      },
    });
    
    console.log(`✅ Created appointment for ${appointmentTime.toLocaleString()}`);
    console.log(`   Appointment ID: ${appointment.id}`);
    
    // 4. Manually schedule booking confirmation reminder
    console.log('4️⃣ Scheduling booking confirmation...');
    
    const template = await prisma.reminderTemplate.findFirst({
      where: { 
        clinicId: clinic.id,
        trigger: 'booking_confirmed',
        isActive: true
      }
    });
    
    if (!template) {
      console.log('❌ No booking_confirmed template found!');
      return;
    }
    
    const reminder = await prisma.scheduledReminder.create({
      data: {
        appointmentId: appointment.id,
        templateId: template.id,
        scheduledFor: new Date(), // Send immediately
      },
    });
    
    console.log(`✅ Scheduled reminder: ${template.trigger}`);
    
    // 5. Wait a moment for processing
    console.log('5️⃣ Waiting for processing...');
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    // 6. Trigger cron manually
    console.log('6️⃣ Triggering cron to send 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 executed:', cronResult);
      
      if (cronResult.sent > 0) {
        console.log('🎉 SUCCESS! Reminder was sent!');
      } else if (cronResult.failed > 0) {
        console.log('❌ Reminder failed to send');
      } else {
        console.log('⚠️ No reminders were processed');
      }
    } else {
      console.log('❌ Cron failed:', cronResponse.status);
    }
    
    // 7. Check final status
    console.log('7️⃣ Checking final status...');
    
    const updatedReminder = await prisma.scheduledReminder.findUnique({
      where: { id: reminder.id }
    });
    
    console.log(`   Reminder status: ${updatedReminder.status}`);
    
    const messageLog = await prisma.messageLog.findFirst({
      where: { 
        appointmentId: appointment.id,
        phone: lead.phone
      }
    });
    
    if (messageLog) {
      console.log('✅ Message logged successfully!');
      console.log(`   Status: ${messageLog.status}`);
      console.log(`   Message: "${messageLog.message.substr(0, 50)}..."`);
    } else {
      console.log('❌ No message found in log');
    }
    
    console.log('\n📱 CHECK YOUR WHATSAPP NOW!');
    console.log(`   Number: ${lead.phone}`);
    console.log('   You should have received a booking confirmation message.');
    
  } catch (error) {
    console.error('❌ Workflow test failed:', error);
  } finally {
    await prisma.$disconnect();
  }
}

testCompleteWorkflow().catch(console.error);