// Test creating appointment through the actual API
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function testAppointmentCreation() {
  console.log('🧪 Testing Real Appointment API...');
  
  try {
    // Get clinic, lead, and treatment
    const clinic = await prisma.clinic.findFirst();
    const lead = await prisma.lead.findFirst({ where: { clinicId: clinic.id } });
    const treatment = await prisma.treatment.findFirst({ where: { clinicId: clinic.id } });
    
    console.log(`✅ Clinic: ${clinic.name} (ID: ${clinic.id})`);
    console.log(`✅ Lead: ${lead.name} (${lead.phone})`);
    console.log(`✅ Treatment: ${treatment.name} (${treatment.duration} min)`);
    
    // Check active templates
    const templates = await prisma.reminderTemplate.count({
      where: { clinicId: clinic.id, isActive: true }
    });
    console.log(`✅ Active templates: ${templates}`);
    
    if (templates === 0) {
      console.log('❌ No active templates - fixing...');
      const { execSync } = require('child_process');
      execSync('node fix-templates.js', { cwd: process.cwd() });
    }
    
    // Create appointment data
    const appointmentData = {
      leadId: lead.id,
      treatmentId: treatment.id,
      dateTime: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(), // 2 hours from now
      notes: 'Test appointment via API'
    };
    
    console.log('\n📝 Creating appointment via API...');
    console.log('   DateTime:', appointmentData.dateTime);
    
    // Login to get session (simulate authenticated request)
    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:', await loginResponse.text());
      return;
    }
    
    const cookies = loginResponse.headers.get('set-cookie');
    console.log('✅ Login successful');
    
    // Create appointment
    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) {
      console.log('❌ Appointment creation failed:', appointmentResponse.status, await appointmentResponse.text());
      return;
    }
    
    const appointment = await appointmentResponse.json();
    console.log('✅ Appointment created:', appointment.id);
    
    // Wait a moment for reminders to be scheduled
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    // Check if reminders were scheduled
    const reminders = await prisma.scheduledReminder.findMany({
      where: { appointmentId: appointment.id },
      include: { template: true }
    });
    
    console.log(`\n📅 Reminders scheduled: ${reminders.length}`);
    reminders.forEach(r => {
      console.log(`   - ${r.template.trigger} at ${r.scheduledFor} (${r.status})`);
    });
    
    if (reminders.length === 0) {
      console.log('❌ ERROR: No reminders were scheduled!');
      console.log('   This is the main issue preventing reminders from working.');
    } else {
      console.log('✅ Reminders were properly scheduled!');
    }
    
    // Test cron processing
    console.log('\n⏰ Testing cron processing...');
    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:', cronResult);
      
      if (cronResult.sent > 0) {
        console.log('🎉 SUCCESS! Reminders are being sent!');
      } else {
        console.log('⚠️ No reminders sent - check timing and templates');
      }
    } else {
      console.log('❌ Cron failed:', cronResponse.status);
    }
    
  } catch (error) {
    console.error('❌ Test failed:', error);
  } finally {
    await prisma.$disconnect();
  }
}

testAppointmentCreation().catch(console.error);