// Test exact UI workflow with authentication
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function testUIExactWorkflow() {
  console.log('🔍 TESTING EXACT UI WORKFLOW');
  console.log('='.repeat(50));
  
  try {
    // 1. Get data like UI would
    console.log('1️⃣ Getting clinic data...');
    const clinic = await prisma.clinic.findFirst();
    console.log(`   Clinic: ${clinic.name} (WAHA: ${clinic.wahaStatus})`);
    
    // 2. Get treatments like UI would  
    console.log('2️⃣ Getting treatments...');
    const treatments = await prisma.treatment.findMany({
      where: { clinicId: clinic.id, isActive: true }
    });
    console.log(`   Available treatments: ${treatments.length}`);
    
    // 3. Get leads like UI would
    console.log('3️⃣ Getting leads...');
    const leads = await prisma.lead.findMany({
      where: { clinicId: clinic.id }
    });
    console.log(`   Available leads: ${leads.length}`);
    
    if (treatments.length === 0 || leads.length === 0) {
      console.log('❌ Missing data for test');
      return;
    }
    
    // 4. Check reminder templates
    console.log('4️⃣ Checking reminder templates...');
    const templates = await prisma.reminderTemplate.findMany({
      where: { clinicId: clinic.id, isActive: true }
    });
    console.log(`   Active templates: ${templates.length}`);
    
    if (templates.length === 0) {
      console.log('❌ NO ACTIVE TEMPLATES! This is the problem.');
      console.log('🔧 Running fix...');
      
      const { execSync } = require('child_process');
      execSync('node fix-templates.js');
      
      console.log('✅ Templates fixed, retesting...');
      return;
    }
    
    templates.forEach(t => {
      console.log(`      - ${t.trigger} (offset: ${t.offsetMinutes} min)`);
    });
    
    // 5. Login exactly like UI
    console.log('5️⃣ Logging in like UI...');
    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('✅ Authenticated');
    
    // 6. Create appointment exactly like UI  
    console.log('6️⃣ Creating appointment via API...');
    
    const appointmentData = {
      leadId: leads[0].id,
      treatmentId: treatments[0].id,
      dateTime: new Date(Date.now() + 30 * 60 * 1000).toISOString(), // 30 min from now
      notes: 'UI Test Appointment'
    };
    
    console.log(`   Lead: ${leads[0].name} (${leads[0].phone})`);
    console.log(`   Treatment: ${treatments[0].name}`);
    console.log(`   DateTime: ${appointmentData.dateTime}`);
    
    const beforeCounts = {
      appointments: await prisma.appointment.count(),
      reminders: await prisma.scheduledReminder.count(),
      messages: await prisma.messageLog.count()
    };
    
    const appointmentResponse = await fetch('http://localhost:3000/api/appointments', {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'Cookie': cookies
      },
      body: JSON.stringify(appointmentData)
    });
    
    if (!appointmentResponse.ok) {
      const error = await appointmentResponse.text();
      console.log('❌ Appointment creation failed:', appointmentResponse.status, error);
      return;
    }
    
    const appointment = await appointmentResponse.json();
    console.log(`✅ Appointment created: ${appointment.id}`);
    
    // 7. Check what changed immediately
    console.log('7️⃣ Checking immediate changes...');
    await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds
    
    const afterCounts = {
      appointments: await prisma.appointment.count(),
      reminders: await prisma.scheduledReminder.count(),
      messages: await prisma.messageLog.count()
    };
    
    console.log(`   Appointments: ${beforeCounts.appointments} → ${afterCounts.appointments}`);
    console.log(`   Reminders: ${beforeCounts.reminders} → ${afterCounts.reminders}`);
    console.log(`   Messages: ${beforeCounts.messages} → ${afterCounts.messages}`);
    
    // 8. Get appointment details
    const fullAppointment = await prisma.appointment.findUnique({
      where: { id: appointment.id },
      include: {
        lead: true,
        treatment: true,
        clinic: true,
        scheduledReminders: {
          include: { template: true }
        }
      }
    });
    
    console.log('8️⃣ Appointment details:');
    console.log(`   Confirm Token: ${fullAppointment.confirmToken ? '✅' : '❌'}`);
    console.log(`   Reminders: ${fullAppointment.scheduledReminders.length}`);
    
    if (fullAppointment.scheduledReminders.length === 0) {
      console.log('❌ NO REMINDERS SCHEDULED!');
      console.log('🔍 Investigating...');
      
      // Test reminder scheduling manually
      console.log('🧪 Testing scheduleReminders function manually...');
      
      try {
        // Import and test the function directly
        const { scheduleReminders } = await import('./src/lib/reminders.js');
        await scheduleReminders(appointment.id);
        console.log('✅ Manual reminder scheduling completed');
        
        // Check again
        const updatedAppointment = await prisma.appointment.findUnique({
          where: { id: appointment.id },
          include: { scheduledReminders: { include: { template: true } } }
        });
        
        console.log(`   Now has ${updatedAppointment.scheduledReminders.length} reminders`);
        
      } catch (error) {
        console.log(`❌ Manual scheduling failed: ${error.message}`);
      }
      
    } else {
      console.log('✅ Reminders properly scheduled:');
      fullAppointment.scheduledReminders.forEach(r => {
        console.log(`   - ${r.template.trigger} at ${r.scheduledFor} (${r.status})`);
      });
    }
    
    // 9. Test cron
    console.log('9️⃣ Testing cron...');
    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}, skipped=${cronResult.skipped}`);
    } else {
      console.log('❌ Cron failed');
    }
    
    // 10. Final status
    const finalCounts = {
      appointments: await prisma.appointment.count(),
      reminders: await prisma.scheduledReminder.count(),
      messages: await prisma.messageLog.count()
    };
    
    console.log('\n📊 FINAL RESULTS:');
    console.log(`   Appointments: ${beforeCounts.appointments} → ${finalCounts.appointments}`);
    console.log(`   Reminders: ${beforeCounts.reminders} → ${finalCounts.reminders}`);
    console.log(`   Messages: ${beforeCounts.messages} → ${finalCounts.messages}`);
    
    if (finalCounts.messages > beforeCounts.messages) {
      console.log('🎉 SUCCESS! Messages were sent!');
    } else {
      console.log('❌ FAILURE! No messages sent!');
    }
    
  } catch (error) {
    console.error('❌ Test failed:', error);
  } finally {
    await prisma.$disconnect();
  }
}

testUIExactWorkflow().catch(console.error);