const { Sequelize } = require('sequelize');
require('dotenv').config();

const sequelize = new Sequelize(process.env.DATABASE_URL, {
  logging: false,
});

async function testAvailableUsers() {
  try {
    await sequelize.authenticate();
    console.log('Database connected successfully');

    // Find the "Om Sri Sai Chit" group
    const [groups] = await sequelize.query(`
      SELECT id, name FROM chit_groups WHERE name = 'Om Sri Sai Chit'
    `);
    
    if (groups.length === 0) {
      console.log('No "Om Sri Sai Chit" group found');
      return;
    }
    
    const groupId = groups[0].id;
    console.log(`Found group: ${groups[0].name} (ID: ${groupId})`);

    // Get existing members of this group
    const [members] = await sequelize.query(`
      SELECT gm.user_id, u.full_name, u.mobile_number 
      FROM group_members gm 
      JOIN users u ON gm.user_id = u.id 
      WHERE gm.group_id = $1 AND gm.status = 'active'
    `, [groupId]);
    
    console.log(`\nExisting members (${members.length}):`);
    members.forEach((member, index) => {
      console.log(`${index + 1}. ${member.full_name} (${member.mobile_number}) - ID: ${member.user_id}`);
    });

    // Get all active member users
    const [allUsers] = await sequelize.query(`
      SELECT id, full_name, mobile_number 
      FROM users 
      WHERE role = 'member' AND is_active = true
      ORDER BY full_name
    `);
    
    console.log(`\nAll active member users (${allUsers.length}):`);
    allUsers.forEach((user, index) => {
      const isMember = members.some(m => m.user_id === user.id);
      console.log(`${index + 1}. ${user.full_name} (${user.mobile_number}) - ID: ${user.id} ${isMember ? '[ALREADY MEMBER]' : '[AVAILABLE]'}`);
    });

    // Test the exact query from the API
    console.log(`\n=== Testing API Query ===`);
    const [availableUsers] = await sequelize.query(`
      SELECT id, full_name, mobile_number, email, address, emergency_contact, created_at
      FROM users 
      WHERE is_active = true 
        AND role = 'member'
        AND id NOT IN (
          SELECT user_id FROM group_members 
          WHERE group_id = $1 AND status = 'active'
        )
      ORDER BY full_name
    `, [groupId]);
    
    console.log(`Available users for group (${availableUsers.length}):`);
    availableUsers.forEach((user, index) => {
      console.log(`${index + 1}. ${user.full_name} (${user.mobile_number}) - ID: ${user.id}`);
    });

    console.log(`\nSummary:`);
    console.log(`- Total users: ${allUsers.length}`);
    console.log(`- Existing members: ${members.length}`);
    console.log(`- Available to add: ${availableUsers.length}`);

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await sequelize.close();
  }
}

testAvailableUsers();
