// Test with clean lead to avoid conflicts
const { PrismaClient } = require('@prisma/client');
const crypto = require('crypto');
const prisma = new PrismaClient();

async function testCleanWorkflow() {
  console.log('🧪 TESTING CLEAN WORKFLOW (No Conflicts)');
  console.log('='.repeat(60));
  
  try {
    // 1. Get clinic
    const clinic = await prisma.clinic.findFirst();
    console.log(`✅ Clinic: ${clinic.name} (WAHA: ${clinic.wahaStatus})`);
    
    // 2. Check templates first
    const templates = await prisma.reminderTemplate.count({
      where: { clinicId: clinic.id, isActive: true }
    });
    console.log(`✅ Active templates: ${templates}`);
    
    if (templates === 0) {
      console.log('🔧 Fixing templates...');
      const { execSync } = require('child_process');
      execSync('node fix-templates.js');
      console.log('✅ Templates fixed');
    }
    
    // 3. Create a fresh lead to avoid conflicts
    console.log('👤 Creating fresh test lead...');
    
    // Clean up any existing test leads first
    await prisma.scheduledReminder.deleteMany({
      where: { appointment: { lead: { name: 'CLEAN_TEST_USER' } } }
    });
    await prisma.appointment.deleteMany({
      where: { lead: { name: 'CLEAN_TEST_USER' } }
    });
    await prisma.lead.deleteMany({
      where: { name: 'CLEAN_TEST_USER' }
    });
    
    const lead = await prisma.lead.create({
      data: {
        clinicId: clinic.id,
        name: 'CLEAN_TEST_USER',
        phone: '+96170774480', // Your number to receive test
        status: 'new',
        source: 'test'
      }
    });
    console.log(`✅ Created lead: ${lead.name} (${lead.phone})`);
    
    // 4. Get treatment
    const treatment = await prisma.treatment.findFirst({
      where: { clinicId: clinic.id, isActive: true }
    });
    console.log(`✅ Treatment: ${treatment.name}`);
    
    // 5. Login
    console.log('🔐 Logging in...');
    const loginResponse = await fetch('http://localhost:3000/api/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: 'admin@clinera.com',
        password: 'admin123'
      })
    });
    
    if (!loginResponse.ok) {
      console.log('❌ Login failed');
      return;
    }
    
    const cookies = loginResponse.headers.get('set-cookie');
    console.log('✅ Login successful');
    
    // 6. Count before creation
    const before = {
      appointments: await prisma.appointment.count(),
      reminders: await prisma.scheduledReminder.count(),
      messages: await prisma.messageLog.count()
    };
    console.log(`📊 Before: ${before.appointments} appointments, ${before.reminders} reminders, ${before.messages} messages`);
    
    // 7. Create appointment
    console.log('📝 Creating appointment...');
    const appointmentTime = new Date(Date.now() + 60 * 60 * 1000); // 1 hour from now
    
    const appointmentData = {
      leadId: lead.id,
      treatmentId: treatment.id,
      dateTime: appointmentTime.toISOString(),
      notes: 'Clean test appointment'
    };
    
    console.log(`   Time: ${appointmentTime.toLocaleString()}`);
    
    const appointmentResponse = await fetch('http://localhost:3000/api/appointments', {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'Cookie': cookies
      },
      body: JSON.stringify(appointmentData)
    });
    
    console.log(`📡 API Response: ${appointmentResponse.status}`);
    
    if (!appointmentResponse.ok) {
      const error = await appointmentResponse.text();
      console.log('❌ APPOINTMENT CREATION FAILED:');
      console.log('   Status:', appointmentResponse.status);
      console.log('   Error:', error);
      return;
    }
    
    const appointment = await appointmentResponse.json();
    console.log(`✅ APPOINTMENT CREATED: ${appointment.id}`);
    
    // 8. Wait for background processes
    console.log('⏳ Waiting for reminder scheduling...');
    await new Promise(resolve => setTimeout(resolve, 5000)); // Wait 5 seconds
    
    // 9. Check what happened
    const after = {
      appointments: await prisma.appointment.count(),
      reminders: await prisma.scheduledReminder.count(),
      messages: await prisma.messageLog.count()
    };
    
    console.log(`📊 After: ${after.appointments} appointments, ${after.reminders} reminders, ${after.messages} messages`);
    
    const changes = {
      appointments: after.appointments - before.appointments,
      reminders: after.reminders - before.reminders,
      messages: after.messages - before.messages
    };
    
    console.log(`📈 Changes: +${changes.appointments} appointments, +${changes.reminders} reminders, +${changes.messages} messages`);
    
    // 10. Get full appointment details
    const fullAppointment = await prisma.appointment.findUnique({
      where: { id: appointment.id },
      include: {
        scheduledReminders: {
          include: { template: true },
          orderBy: { scheduledFor: 'asc' }
        }
      }
    });
    
    console.log('\n📋 APPOINTMENT DETAILS:');
    console.log(`   ID: ${fullAppointment.id}`);
    console.log(`   Status: ${fullAppointment.status}`);
    console.log(`   Confirm Token: ${fullAppointment.confirmToken ? 'YES ✅' : 'NO ❌'}`);
    console.log(`   Reminders Scheduled: ${fullAppointment.scheduledReminders.length}`);
    
    if (fullAppointment.scheduledReminders.length === 0) {
      console.log('❌ NO REMINDERS SCHEDULED - THIS IS THE PROBLEM!');
      
      // Try to schedule them manually
      console.log('🔧 Attempting manual reminder scheduling...');
      try {
        const { scheduleReminders } = await import('./src/lib/reminders.js');
        await scheduleReminders(fullAppointment.id);
        
        // Check again
        const updated = await prisma.appointment.findUnique({
          where: { id: fullAppointment.id },
          include: { scheduledReminders: { include: { template: true } } }
        });
        
        console.log(`✅ Manual scheduling result: ${updated.scheduledReminders.length} reminders`);
        
      } catch (error) {
        console.log(`❌ Manual scheduling failed: ${error.message}`);
        console.log(`   Stack: ${error.stack}`);
      }
      
    } else {
      console.log('✅ REMINDERS FOUND:');
      fullAppointment.scheduledReminders.forEach((r, i) => {
        console.log(`   ${i + 1}. ${r.template.trigger} - ${r.scheduledFor} (${r.status})`);
      });
      
      // Check if any are due now
      const dueNow = fullAppointment.scheduledReminders.filter(r => 
        r.status === 'pending' && new Date(r.scheduledFor) <= new Date()
      );
      
      console.log(`⏰ Due now: ${dueNow.length}`);
      
      if (dueNow.length > 0) {
        console.log('🚀 Testing cron to send due reminders...');
        
        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: sent=${cronResult.sent}, failed=${cronResult.failed}, skipped=${cronResult.skipped}`);
          
          if (cronResult.sent > 0) {
            console.log('🎉 SUCCESS! Reminders were sent!');
            console.log('📱 CHECK YOUR WHATSAPP NOW!');
          }
        }
      }
    }
    
    // 11. Final verdict
    console.log('\n🎯 FINAL VERDICT:');
    if (changes.appointments === 1 && changes.reminders > 0) {
      console.log('🟢 WORKING: Appointment created AND reminders scheduled');
    } else if (changes.appointments === 1 && changes.reminders === 0) {
      console.log('🟡 PARTIAL: Appointment created but NO reminders scheduled');
      console.log('   🔍 Issue: scheduleReminders() function not working');
    } else if (changes.appointments === 0) {
      console.log('🔴 BROKEN: Appointment not created at all');
      console.log('   🔍 Issue: API endpoint failing');
    }
    
  } catch (error) {
    console.error('❌ Test completely failed:', error);
  } finally {
    await prisma.$disconnect();
  }
}

testCleanWorkflow().catch(console.error);