const axios = require('axios');

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

async function testGroupsByUserIdAPI() {
    console.log('👥 Testing Groups by User ID API\n');
    
    try {
        // Test 1: Get groups by user ID (Primary endpoint)
        console.log('📋 Test 1: Get groups by user ID (Primary endpoint)');
        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));
        
        // Check if groups are present
        if (response1.data.data?.groups?.length > 0) {
            console.log(`✅ Found ${response1.data.data.groups.length} groups for user`);
            response1.data.data.groups.forEach((group, index) => {
                console.log(`  ${index + 1}. ${group.groupType} - ${group.groupName}`);
            });
        } else {
            console.log('ℹ️  No groups found for user');
        }
        console.log('---\n');
        
        // Test 2: Get groups by user ID (Alternative endpoint)
        console.log('📋 Test 2: Get groups by user ID (Alternative endpoint)');
        console.log(`GET /api/groups/user/${testUserId}/groups`);
        const response2 = await axios.get(`${BASE_URL}/groups/user/${testUserId}/groups`);
        console.log('✅ Status:', response2.status);
        console.log('📊 Response:', JSON.stringify(response2.data, null, 2));
        
        // Check if groups are present
        if (response2.data.data?.groups?.length > 0) {
            console.log(`✅ Found ${response2.data.data.groups.length} groups created by user`);
            response2.data.data.groups.forEach((group, index) => {
                console.log(`  ${index + 1}. ${group.groupType} - ${group.groupName} (Members: ${group.memberCount})`);
            });
        } else {
            console.log('ℹ️  No groups created by user');
        }
        console.log('---\n');
        
        // Test 3: Get school groups only
        console.log('📋 Test 3: Get school groups only');
        console.log(`GET /api/groups/user/${testUserId}/groups?groupType=school`);
        const response3 = await axios.get(`${BASE_URL}/groups/user/${testUserId}/groups?groupType=school`);
        console.log('✅ Status:', response3.status);
        console.log('📊 Response:', JSON.stringify(response3.data, null, 2));
        console.log('---\n');
        
        // Test 4: Get college groups only
        console.log('📋 Test 4: Get college groups only');
        console.log(`GET /api/groups/user/${testUserId}/groups?groupType=college`);
        const response4 = await axios.get(`${BASE_URL}/groups/user/${testUserId}/groups?groupType=college`);
        console.log('✅ Status:', response4.status);
        console.log('📊 Response:', JSON.stringify(response4.data, null, 2));
        console.log('---\n');
        
        // Test 5: Get professional groups only
        console.log('📋 Test 5: Get professional groups only');
        console.log(`GET /api/groups/user/${testUserId}/groups?groupType=professional`);
        const response5 = await axios.get(`${BASE_URL}/groups/user/${testUserId}/groups?groupType=professional`);
        console.log('✅ Status:', response5.status);
        console.log('📊 Response:', JSON.stringify(response5.data, null, 2));
        console.log('---\n');
        
        // Test 6: Test with invalid user ID
        console.log('📋 Test 6: Test with invalid user ID');
        console.log('GET /api/groups/user/invalid_user_id');
        try {
            const response6 = await axios.get(`${BASE_URL}/groups/user/invalid_user_id`);
            console.log('❌ Unexpected success:', response6.data);
        } catch (error) {
            if (error.response?.status === 404) {
                console.log('✅ Correctly returns 404 Not Found for invalid user ID');
                console.log('📊 Error Response:', JSON.stringify(error.response.data, null, 2));
            } else {
                console.log('❌ Unexpected error:', error.response?.data || error.message);
            }
        }
        console.log('---\n');
        
        // Test 7: Test with non-existent user ID
        console.log('📋 Test 7: Test with non-existent user ID');
        console.log('GET /api/groups/user/68c7ef413c86477b3b626999');
        try {
            const response7 = await axios.get(`${BASE_URL}/groups/user/68c7ef413c86477b3b626999`);
            console.log('✅ Status:', response7.status);
            console.log('📊 Response:', JSON.stringify(response7.data, null, 2));
            
            if (response7.data.data.groups.length === 0) {
                console.log('✅ Correctly returns empty array for non-existent user');
            }
        } catch (error) {
            console.log('❌ Unexpected error:', error.response?.data || error.message);
        }
        console.log('---\n');
        
        // Test 8: Get all groups (for comparison)
        console.log('📋 Test 8: Get all groups (for comparison)');
        console.log('GET /api/groups');
        const response8 = await axios.get(`${BASE_URL}/groups`);
        console.log('✅ Status:', response8.status);
        console.log('📊 Response:', JSON.stringify(response8.data, null, 2));
        console.log('---\n');
        
        // Test 9: Get group by ID (if we have a group ID from previous responses)
        if (response1.data.data?.groups?.length > 0) {
            const groupId = response1.data.data.groups[0].groupId;
            console.log('📋 Test 9: Get group by ID');
            console.log(`GET /api/groups/${groupId}`);
            const response9 = await axios.get(`${BASE_URL}/groups/${groupId}`);
            console.log('✅ Status:', response9.status);
            console.log('📊 Response:', JSON.stringify(response9.data, null, 2));
            console.log('---\n');
        }
        
        console.log('🎯 API Endpoints Summary:');
        console.log('✅ GET /api/groups/user/:userId - Get groups associated with user (Recommended)');
        console.log('✅ GET /api/groups/user/:userId/groups - Get groups created by user');
        console.log('✅ GET /api/groups/user/:userId/groups?groupType=school - Filter by group type');
        console.log('✅ GET /api/groups/user/:userId/groups?groupType=college - Filter by group type');
        console.log('✅ GET /api/groups/user/:userId/groups?groupType=professional - Filter by group type');
        console.log('✅ GET /api/groups - Get all groups');
        console.log('✅ GET /api/groups/:groupId - Get specific group by ID');
        
    } catch (error) {
        console.error('❌ Test failed:', error.response?.data || error.message);
        console.error('❌ Full error:', error);
        
        if (error.response?.status === 404) {
            console.log('\n💡 Route not found. Please check:');
            console.log('1. Server is running on the correct port');
            console.log('2. Group routes are properly registered in server.js');
            console.log('3. Route paths are correct');
        }
    }
}

// Run the test
testGroupsByUserIdAPI();
