const axios = require('axios');

const BASE_URL = 'http://localhost:5500/api';
const testUserId = '68c7ef413c86477b3b626172'; // Replace with actual user ID

async function testEnhancedGroupsByUserIdAPI() {
    console.log('👥 Testing Enhanced Groups by User ID API\n');
    
    try {
        // Test 1: Get enhanced groups by user ID
        console.log('📋 Test 1: Get enhanced groups by user ID');
        console.log(`GET /api/groups/user/${testUserId}`);
        const response1 = await axios.get(`${BASE_URL}/groups/user/${testUserId}`);
        console.log('✅ Status:', response1.status);
        console.log('📊 Response:', JSON.stringify(response1.data, null, 2));
        
        // Analyze the response
        if (response1.data.success) {
            const data = response1.data.data;
            console.log('\n🔍 Analysis:');
            console.log(`👤 User: ${data.user.name} (${data.user.mobile})`);
            console.log(`📊 Summary:`, data.summary);
            
            if (data.groups && data.groups.length > 0) {
                console.log('\n📋 Groups Details:');
                data.groups.forEach((group, index) => {
                    console.log(`  ${index + 1}. ${group.groupType.toUpperCase()} - ${group.groupName}`);
                    console.log(`     📊 Member Count: ${group.memberCount}`);
                    console.log(`     👥 Members Array Count: ${group.membersCount}`);
                    console.log(`     ✅ User is Member: ${group.isUserMember ? 'YES' : 'NO'}`);
                    console.log(`     🎯 Group ID: ${group.groupId}`);
                    console.log(`     📅 Created: ${group.createdAt}`);
                    console.log('');
                });
            } else {
                console.log('ℹ️  No groups found for user');
            }
        }
        console.log('---\n');
        
        // Test 2: Test with different user ID
        console.log('📋 Test 2: Test with different user ID');
        const testUserId2 = '68c7ef413c86477b3b626173'; // Replace with another valid user ID
        console.log(`GET /api/groups/user/${testUserId2}`);
        try {
            const response2 = await axios.get(`${BASE_URL}/groups/user/${testUserId2}`);
            console.log('✅ Status:', response2.status);
            console.log('📊 Response:', JSON.stringify(response2.data, null, 2));
            
            if (response2.data.success && response2.data.data.groups.length > 0) {
                console.log('\n🔍 Analysis for User 2:');
                const data2 = response2.data.data;
                console.log(`👤 User: ${data2.user.name} (${data2.user.mobile})`);
                console.log(`📊 Summary:`, data2.summary);
            }
        } catch (error) {
            if (error.response?.status === 404) {
                console.log('✅ User not found (expected for test user ID)');
            } else {
                console.log('❌ Unexpected error:', error.response?.data || error.message);
            }
        }
        console.log('---\n');
        
        // Test 3: Test member checking logic
        console.log('📋 Test 3: Analyze member checking logic');
        if (response1.data.success && response1.data.data.groups.length > 0) {
            const groups = response1.data.data.groups;
            console.log('🔍 Member Checking Analysis:');
            
            groups.forEach((group, index) => {
                console.log(`\n📋 Group ${index + 1}: ${group.groupName}`);
                console.log(`   📊 memberCount (from Group model): ${group.memberCount}`);
                console.log(`   👥 membersCount (from members array): ${group.membersCount}`);
                console.log(`   ✅ isUserMember: ${group.isUserMember}`);
                
                if (group.members && group.members.length > 0) {
                    console.log(`   👥 Members in array:`);
                    group.members.forEach((member, memberIndex) => {
                        const isCurrentUser = member.isCurrentUser;
                        console.log(`      ${memberIndex + 1}. ${member.name} (${member.role}) ${isCurrentUser ? '👤 [CURRENT USER]' : ''}`);
                    });
                }
            });
        }
        console.log('---\n');
        
        // Test 4: Test user group IDs
        console.log('📋 Test 4: Analyze user group IDs');
        if (response1.data.success) {
            const user = response1.data.data.user;
            console.log('👤 User Group IDs:');
            console.log(`   🏫 School Group ID: ${user.schoolGroupId || 'None'}`);
            console.log(`   🎓 College Group ID: ${user.collegeGroupId || 'None'}`);
            console.log(`   💼 Professional Group ID: ${user.professionalGroupId || 'None'}`);
            
            // Check if group IDs match the returned groups
            const returnedGroupIds = response1.data.data.groups.map(g => g.groupId);
            console.log('\n🔍 Group ID Matching:');
            console.log(`   📊 Returned Group IDs: ${returnedGroupIds.join(', ')}`);
            
            if (user.schoolGroupId && returnedGroupIds.includes(user.schoolGroupId)) {
                console.log(`   ✅ School Group ID found in results`);
            }
            if (user.collegeGroupId && returnedGroupIds.includes(user.collegeGroupId)) {
                console.log(`   ✅ College Group ID found in results`);
            }
            if (user.professionalGroupId && returnedGroupIds.includes(user.professionalGroupId)) {
                console.log(`   ✅ Professional Group ID found in results`);
            }
        }
        console.log('---\n');
        
        console.log('🎯 Enhanced API Features Summary:');
        console.log('✅ Fetches user from User model first');
        console.log('✅ Gets schoolGroupId, collegeGroupId, professionalGroupId');
        console.log('✅ Finds groups using those IDs');
        console.log('✅ Checks if user is in members array');
        console.log('✅ Returns isUserMember status for each group');
        console.log('✅ Returns memberCount and membersCount');
        console.log('✅ Provides summary statistics');
        console.log('✅ Includes detailed member information');
        console.log('✅ Shows which member is the current user');
        
    } catch (error) {
        console.error('❌ Test failed:', error.response?.data || error.message);
        console.error('❌ Full error:', error);
        
        if (error.response?.status === 404) {
            console.log('\n💡 User not found. Please:');
            console.log('1. Replace testUserId with a valid user ID');
            console.log('2. Make sure the user exists in the database');
            console.log('3. Check if the user has any group IDs assigned');
        }
    }
}

// Run the test
testEnhancedGroupsByUserIdAPI();
