// Complete system status check
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function systemStatus() {
  console.log('📊 CLINERA REMINDER SYSTEM STATUS');
  console.log('='.repeat(40));
  
  try {
    // 1. Database counts
    const counts = await Promise.all([
      prisma.clinic.count(),
      prisma.reminderTemplate.count({ where: { isActive: true } }),
      prisma.appointment.count(),
      prisma.scheduledReminder.count(),
      prisma.messageLog.count({ where: { direction: 'outgoing' } })
    ]);
    
    console.log('📊 Database Status:');
    console.log(`   Clinics: ${counts[0]}`);
    console.log(`   Active Templates: ${counts[1]}`);
    console.log(`   Appointments: ${counts[2]}`);
    console.log(`   Scheduled Reminders: ${counts[3]}`);
    console.log(`   Messages Sent: ${counts[4]}`);
    
    // 2. Check clinic status
    const clinic = await prisma.clinic.findFirst();
    console.log('\n🏥 Clinic Status:');
    console.log(`   Name: ${clinic.name}`);
    console.log(`   WAHA Status: ${clinic.wahaStatus}`);
    console.log(`   Session: ${clinic.wahaSessionId}`);
    
    // 3. Check recent activity
    const recentMessages = await prisma.messageLog.count({
      where: {
        direction: 'outgoing',
        sentAt: { gte: new Date(Date.now() - 60 * 60 * 1000) } // last hour
      }
    });
    
    const recentAppointments = await prisma.appointment.count({
      where: {
        createdAt: { gte: new Date(Date.now() - 60 * 60 * 1000) } // last hour
      }
    });
    
    console.log('\n📈 Recent Activity (Last Hour):');
    console.log(`   New Appointments: ${recentAppointments}`);
    console.log(`   Messages Sent: ${recentMessages}`);
    
    // 4. Check pending reminders
    const pendingReminders = await prisma.scheduledReminder.findMany({
      where: { status: 'pending' },
      include: {
        appointment: { include: { lead: true } },
        template: true
      },
      take: 5
    });
    
    console.log(`\n⏰ Pending Reminders: ${pendingReminders.length}`);
    pendingReminders.forEach(r => {
      console.log(`   - ${r.template.trigger} for ${r.appointment.lead.name} at ${r.scheduledFor}`);
    });
    
    // 5. Test WAHA connection
    console.log('\n📱 WAHA Connection Test:');
    try {
      const wahaResponse = await fetch('http://localhost:3005/api/sessions', {
        headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
      });
      
      if (wahaResponse.ok) {
        const sessions = await wahaResponse.json();
        const defaultSession = sessions.find(s => s.name === 'default');
        console.log(`   Status: ${defaultSession ? defaultSession.status : 'NOT FOUND'} ✅`);
      } else {
        console.log(`   Status: ERROR (${wahaResponse.status}) ❌`);
      }
    } catch (error) {
      console.log(`   Status: CONNECTION FAILED ❌`);
    }
    
    // 6. Test cron endpoint
    console.log('\n⏰ Cron Endpoint Test:');
    try {
      const cronResponse = await fetch('http://localhost:3000/api/cron/send-reminders?key=dev-cron-key', {
        method: 'POST'
      });
      
      if (cronResponse.ok) {
        const result = await cronResponse.json();
        console.log(`   Status: WORKING ✅ (${result.durationMs}ms)`);
        console.log(`   Last Run: sent=${result.sent}, failed=${result.failed}`);
      } else {
        console.log(`   Status: ERROR (${cronResponse.status}) ❌`);
      }
    } catch (error) {
      console.log(`   Status: CONNECTION FAILED ❌`);
    }
    
    console.log('\n🎯 OVERALL SYSTEM STATUS:');
    if (counts[1] > 0 && clinic.wahaStatus === 'connected' && counts[4] > 0) {
      console.log('   🟢 FULLY OPERATIONAL');
      console.log('   ✅ Templates configured');
      console.log('   ✅ WAHA connected'); 
      console.log('   ✅ Messages being sent');
      console.log('   ✅ Reminders working perfectly');
    } else {
      console.log('   🟡 NEEDS ATTENTION');
      if (counts[1] === 0) console.log('   ❌ No active templates');
      if (clinic.wahaStatus !== 'connected') console.log('   ❌ WAHA not connected');
      if (counts[4] === 0) console.log('   ❌ No messages sent yet');
    }
    
  } catch (error) {
    console.error('❌ Status check failed:', error);
  } finally {
    await prisma.$disconnect();
  }
}

systemStatus().catch(console.error);