const axios = require('axios');

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

// Test data - Replace with actual IDs from your database
const testUserId = '68c7ef413c86477b3b626172'; // Replace with actual user ID
const testGroupId = '68d2a1ec52d4291170859da5'; // Replace with actual group ID

async function testGetGroupDetails() {
    console.log('🎯 Testing Get Group Details API...\n');
    
    try {
        // Test basic group details
        console.log('1. Testing basic group details:');
        const response1 = await axios.get(`${BASE_URL}/groups/${testGroupId}`);
        
        console.log('✅ Basic Group Details Response:');
        console.log('Status:', response1.status);
        console.log('Group Info:', {
            groupId: response1.data.data.group.groupId,
            groupName: response1.data.data.group.groupName,
            groupType: response1.data.data.group.groupType,
            memberCount: response1.data.data.group.memberCount,
            totalMembers: response1.data.data.statistics.totalMembers
        });
        
        // Test group details with recent messages
        console.log('\n2. Testing group details with recent messages:');
        const response2 = await axios.get(`${BASE_URL}/groups/${testGroupId}?includeMessages=true&messageLimit=5`);
        
        console.log('✅ Group Details with Messages Response:');
        console.log('Status:', response2.status);
        console.log('Recent Messages Count:', response2.data.data.group.recentMessages.length);
        console.log('Statistics:', response2.data.data.statistics);
        
    } catch (error) {
        console.error('❌ Get Group Details 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 testGroupMessages() {
    console.log('\n🎯 Testing Group Messages API...\n');
    
    try {
        // Test get recent messages
        console.log('1. Testing get recent messages:');
        const response1 = await axios.get(`${BASE_URL}/groups/${testGroupId}/messages?limit=10`);
        
        console.log('✅ Recent Messages Response:');
        console.log('Status:', response1.status);
        console.log('Messages Count:', response1.data.data.messages.length);
        console.log('Total Messages:', response1.data.data.pagination.totalMessages);
        
        // Test send a text message
        console.log('\n2. Testing send text message:');
        const response2 = await axios.post(`${BASE_URL}/groups/${testGroupId}/send`, {
            userId: testUserId,
            message: 'Hello from API test!',
            messageType: 'text'
        });
        
        console.log('✅ Send Message Response:');
        console.log('Status:', response2.status);
        console.log('Message ID:', response2.data.data.message._id);
        console.log('Message Content:', response2.data.data.message.message);
        
        // Test search messages
        console.log('\n3. Testing search messages:');
        const response3 = await axios.get(`${BASE_URL}/groups/${testGroupId}/search?searchTerm=Hello&limit=5`);
        
        console.log('✅ Search Messages Response:');
        console.log('Status:', response3.status);
        console.log('Found Messages:', response3.data.data.totalFound);
        
    } catch (error) {
        console.error('❌ Group Messages 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 testWebSocketConnection() {
    console.log('\n🎯 Testing WebSocket Connection...\n');
    
    try {
        const WebSocket = require('ws');
        
        // Test WebSocket connection (this would require a valid JWT token)
        console.log('📡 WebSocket connection test would require:');
        console.log('- Valid JWT token');
        console.log('- User to be member of the group');
        console.log('- WebSocket client implementation');
        console.log('\n💡 WebSocket endpoint: ws://localhost:5500/ws/group-chat');
        console.log('💡 Connection parameters: ?token=<JWT_TOKEN>');
        
        // WebSocket message types supported:
        console.log('\n📋 Supported WebSocket Message Types:');
        console.log('- join_group: { type: "join_group", groupId: "..." }');
        console.log('- leave_group: { type: "leave_group", groupId: "..." }');
        console.log('- send_message: { type: "send_message", groupId: "...", content: "...", messageType: "text" }');
        console.log('- typing_start: { type: "typing_start", groupId: "..." }');
        console.log('- typing_stop: { type: "typing_stop", groupId: "..." }');
        console.log('- ping: { type: "ping" }');
        
        console.log('\n📋 WebSocket Response Types:');
        console.log('- connected: Connection established');
        console.log('- joined_group: Successfully joined group');
        console.log('- new_message: New message received');
        console.log('- user_joined: User joined the group');
        console.log('- user_left: User left the group');
        console.log('- user_typing_start: User started typing');
        console.log('- user_typing_stop: User stopped typing');
        console.log('- recent_messages: Recent messages for the group');
        console.log('- system_message: System-generated message');
        console.log('- error: Error message');
        
    } catch (error) {
        console.error('❌ WebSocket Test Error:', error.message);
    }
}

async function testInvalidScenarios() {
    console.log('\n🎯 Testing Invalid Scenarios...\n');
    
    // Test with invalid group ID
    console.log('1. Testing with invalid group ID:');
    try {
        await axios.get(`${BASE_URL}/groups/000000000000000000000000`);
    } catch (error) {
        if (error.response && error.response.status === 404) {
            console.log('✅ Correctly returned 404 for invalid group ID');
        }
    }
    
    // Test sending message to invalid group
    console.log('\n2. Testing send message to invalid group:');
    try {
        await axios.post(`${BASE_URL}/groups/000000000000000000000000/send`, {
            userId: testUserId,
            message: 'Test message'
        });
    } catch (error) {
        if (error.response && error.response.status === 404) {
            console.log('✅ Correctly returned 404 for invalid group ID');
        }
    }
    
    // Test sending message without required fields
    console.log('\n3. Testing send message without required fields:');
    try {
        await axios.post(`${BASE_URL}/groups/${testGroupId}/send`, {
            message: 'Test message'
            // Missing userId
        });
    } catch (error) {
        if (error.response && error.response.status === 400) {
            console.log('✅ Correctly returned 400 for missing required fields');
        }
    }
}

async function runAllTests() {
    console.log('🚀 Starting Group Details and Chat 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 testGetGroupDetails();
    await testGroupMessages();
    await testWebSocketConnection();
    await testInvalidScenarios();
    
    console.log('\n🎯 All tests completed!');
    console.log('\n📚 API Endpoints Summary:');
    console.log('📋 Group Details:');
    console.log('- GET /api/groups/:groupId - Get complete group details');
    console.log('- GET /api/groups/:groupId?includeMessages=true - Get group with recent messages');
    console.log('\n💬 Group Messages:');
    console.log('- GET /api/groups/:groupId/messages - Get recent messages (limit 500)');
    console.log('- POST /api/groups/:groupId/send - Send text message');
    console.log('- POST /api/groups/:groupId/send (with file) - Send media message');
    console.log('- GET /api/groups/:groupId/search?searchTerm=... - Search messages');
    console.log('- PUT /api/groups/message/:messageId/edit - Edit message');
    console.log('- DELETE /api/groups/message/:messageId - Delete message');
    console.log('- POST /api/groups/message/:messageId/reaction - Add reaction');
    console.log('\n🔌 WebSocket:');
    console.log('- ws://localhost:5500/ws/group-chat?token=<JWT_TOKEN>');
}

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