const db = require('./config/database');

async function testParentChildrenAPI() {
  try {
    console.log('Testing /parent-children/51 API logic...');
    
    const parentId = 51;
    
    // Simulate the exact query from the API
    const [rows] = await db.execute(`
      SELECT c.*, s.name as school_name, d.device_id as device_device_id, d.type as device_type, 
             d.status as device_status, dlb.battery_level, dlb.timestamp as last_update,
             CASE WHEN ds.last_seen > DATE_SUB(NOW(), INTERVAL 15 MINUTE) THEN 'Online' ELSE 'Offline' END as device_online_status,
             latest_sub.max_end_date as subscription_end_date,
             CASE WHEN pl.id IS NOT NULL THEN 'on' ELSE 'off' END as position_lock_status
      FROM children c
      LEFT JOIN schools s ON c.school_id = s.id
      LEFT JOIN devices d ON c.device_id = d.device_id
      LEFT JOIN (
        SELECT device_id, MAX(last_seen) as last_seen
        FROM device_status
        GROUP BY device_id
      ) ds ON ds.device_id = c.device_id
      LEFT JOIN (
        SELECT device_id, battery_level, timestamp
        FROM (
          SELECT 
            device_id,
            battery_level,
            timestamp,
            ROW_NUMBER() OVER (PARTITION BY device_id ORDER BY timestamp DESC) as rn
          FROM device_locations
        ) x
        WHERE x.rn = 1
      ) dlb ON dlb.device_id = c.device_id
      LEFT JOIN (
        SELECT student_id, MAX(end_date) as max_end_date
        FROM student_subscriptions
        GROUP BY student_id
      ) latest_sub ON c.id = latest_sub.student_id
      LEFT JOIN position_lock pl ON pl.device_id = c.device_id AND pl.active = TRUE
      WHERE c.parent_id = ? AND c.parent_id > 0
    `, [parentId]);
    
    console.log('Raw query results:', rows);
    console.log('Number of children found:', rows.length);
    
    // Simulate the mapping logic from the API
    const children = rows.map(child => {
      const name = `${child.first_name} ${child.last_name}`;
      console.log(`Child ID: ${child.id}, first_name: ${child.first_name} (${typeof child.first_name}), last_name: ${child.last_name} (${typeof child.last_name}), combined name: ${name} (${typeof name})`);
      
      return {
        id: child.id,
        name: name,
        grade: `${child.standard} Grade`,
        standard: child.standard,
        division: child.division,
        rollNumber: child.roll_number?.toString(),
        school: child.school_name,
        device: {
          id: child.device_id,
          type: child.device_type || 'GPS Tracker',
          status: child.device_online_status || 'Offline',
          battery: child.battery_level ? `${child.battery_level}%` : '85%',
          lastUpdate: child.last_update ? new Date(child.last_update).toLocaleString() : '2 mins ago',
          subscriptionDays: child.subscription_end_date ? 
            (() => {
              const endDate = new Date(child.subscription_end_date);
              const today = new Date();
              const daysLeft = Math.ceil((endDate - today) / (1000 * 60 * 60 * 24));
              if (daysLeft > 0) {
                return `${daysLeft} days left`;
              } else if (daysLeft === 0) {
                return 'Expires today';
              } else {
                return 'Expired';
              }
            })() : 
            'No Plan'
        }
      };
    });
    
    console.log('\nFinal API response structure:');
    console.log(JSON.stringify(children, null, 2));
    
    // Check if any name is a number
    children.forEach(child => {
      if (typeof child.name === 'number') {
        console.log(`FOUND ISSUE: Child ID ${child.id} has name as number: ${child.name}`);
      }
    });
    
    process.exit(0);
  } catch (error) {
    console.error('Error:', error.message);
    process.exit(1);
  }
}

testParentChildrenAPI();
