const axios = require('axios');

const BASE_URL = 'http://localhost:5500/api';

// Test data
const testUserId = '68c7ef413c86477b3b626172'; // Replace with actual user ID
const testGroupId = '68d2a1ec52d4291170859da5'; // Replace with actual group ID

async function testJoinGroup() {
    console.log('🎯 Testing Join Group API...\n');
    
    try {
        const response = await axios.post(`${BASE_URL}/groups/${testGroupId}/join`, {
            userId: testUserId,
            role: 'member' // Optional: 'member', 'admin', 'moderator'
        });
        
        console.log('✅ Join Group Response:');
        console.log('Status:', response.status);
        console.log('Data:', JSON.stringify(response.data, null, 2));
        
        if (response.data.success) {
            console.log('\n🎉 User successfully joined the group!');
            console.log(`📊 Group now has ${response.data.data.membership.totalMembers} members`);
        }
        
    } catch (error) {
        console.error('❌ Join Group Error:');
        if (error.response) {
            console.error('Status:', error.response.status);
            console.error('Data:', JSON.stringify(error.response.data, null, 2));
        } else {
            console.error('Error:', error.message);
        }
    }
}

async function testLeaveGroup() {
    console.log('\n🎯 Testing Leave Group API...\n');
    
    try {
        const response = await axios.post(`${BASE_URL}/groups/${testGroupId}/leave`, {
            userId: testUserId
        });
        
        console.log('✅ Leave Group Response:');
        console.log('Status:', response.status);
        console.log('Data:', JSON.stringify(response.data, null, 2));
        
        if (response.data.success) {
            console.log('\n🎉 User successfully left the group!');
            console.log(`📊 Group now has ${response.data.data.membership.totalMembers} members`);
        }
        
    } catch (error) {
        console.error('❌ Leave Group Error:');
        if (error.response) {
            console.error('Status:', error.response.status);
            console.error('Data:', JSON.stringify(error.response.data, null, 2));
        } else {
            console.error('Error:', error.message);
        }
    }
}

async function testJoinGroupAgain() {
    console.log('\n🎯 Testing Join Group Again (Should show already member)...\n');
    
    try {
        const response = await axios.post(`${BASE_URL}/groups/${testGroupId}/join`, {
            userId: testUserId,
            role: 'member'
        });
        
        console.log('✅ Join Group Again Response:');
        console.log('Status:', response.status);
        console.log('Data:', JSON.stringify(response.data, null, 2));
        
        if (response.data.success && response.data.data.alreadyMember) {
            console.log('\n✅ Correctly detected that user is already a member!');
        }
        
    } catch (error) {
        console.error('❌ Join Group Again Error:');
        if (error.response) {
            console.error('Status:', error.response.status);
            console.error('Data:', JSON.stringify(error.response.data, null, 2));
        } else {
            console.error('Error:', error.message);
        }
    }
}

async function testGetUserGroups() {
    console.log('\n🎯 Testing Get User Groups (to see membership status)...\n');
    
    try {
        const response = await axios.get(`${BASE_URL}/groups/user/${testUserId}`);
        
        console.log('✅ Get User Groups Response:');
        console.log('Status:', response.status);
        console.log('Data:', JSON.stringify(response.data, null, 2));
        
        if (response.data.success) {
            const groups = response.data.data.groups;
            console.log(`\n📊 User has ${groups.length} groups:`);
            groups.forEach(group => {
                console.log(`- ${group.groupName} (${group.groupType}): isUserMember = ${group.isUserMember}`);
            });
        }
        
    } catch (error) {
        console.error('❌ Get User Groups Error:');
        if (error.response) {
            console.error('Status:', error.response.status);
            console.error('Data:', JSON.stringify(error.response.data, null, 2));
        } else {
            console.error('Error:', error.message);
        }
    }
}

async function testInvalidScenarios() {
    console.log('\n🎯 Testing Invalid Scenarios...\n');
    
    // Test joining non-existent group
    console.log('1. Testing join non-existent group:');
    try {
        await axios.post(`${BASE_URL}/groups/000000000000000000000000/join`, {
            userId: testUserId
        });
    } catch (error) {
        if (error.response && error.response.status === 404) {
            console.log('✅ Correctly returned 404 for non-existent group');
        }
    }
    
    // Test joining with invalid user
    console.log('\n2. Testing join with invalid user:');
    try {
        await axios.post(`${BASE_URL}/groups/${testGroupId}/join`, {
            userId: '000000000000000000000000'
        });
    } catch (error) {
        if (error.response && error.response.status === 404) {
            console.log('✅ Correctly returned 404 for non-existent user');
        }
    }
    
    // Test leaving group without being a member
    console.log('\n3. Testing leave group without being a member:');
    try {
        await axios.post(`${BASE_URL}/groups/${testGroupId}/leave`, {
            userId: '000000000000000000000000'
        });
    } catch (error) {
        if (error.response && error.response.status === 404) {
            console.log('✅ Correctly returned 404 for non-existent user');
        }
    }
}

async function runAllTests() {
    console.log('🚀 Starting Join/Leave Group API Tests...\n');
    console.log(`📋 Test Configuration:`);
    console.log(`- Base URL: ${BASE_URL}`);
    console.log(`- User ID: ${testUserId}`);
    console.log(`- Group ID: ${testGroupId}\n`);
    
    // Test sequence
    await testGetUserGroups(); // Check initial state
    await testJoinGroup(); // Join the group
    await testJoinGroupAgain(); // Try to join again (should show already member)
    await testGetUserGroups(); // Check membership status
    await testLeaveGroup(); // Leave the group
    await testGetUserGroups(); // Check final state
    await testInvalidScenarios(); // Test error cases
    
    console.log('\n🎯 All tests completed!');
}

// Run tests
runAllTests().catch(console.error);
