const Group = require('../models/Group');
const User = require('../models/User');

// Utility function to clean up groups with invalid userId references
const cleanupGroupsWithInvalidUsers = async () => {
    try {
        console.log(`🧹 [GROUP CLEANUP] Starting cleanup of groups with invalid userId references`);
        
        // Find groups where userId doesn't exist in User collection
        const groupsWithInvalidUsers = await Group.aggregate([
            {
                $lookup: {
                    from: 'users',
                    localField: 'userId',
                    foreignField: '_id',
                    as: 'userExists'
                }
            },
            {
                $match: {
                    userId: { $exists: true, $ne: null },
                    userExists: { $size: 0 }
                }
            }
        ]);
        
        if (groupsWithInvalidUsers.length > 0) {
            console.log(`🧹 [GROUP CLEANUP] Found ${groupsWithInvalidUsers.length} groups with invalid userId references`);
            
            // Option 1: Delete these groups (uncomment if you want to delete them)
            // await Group.deleteMany({ _id: { $in: groupsWithInvalidUsers.map(g => g._id) } });
            // console.log(`🧹 [GROUP CLEANUP] Deleted ${groupsWithInvalidUsers.length} groups with invalid userId references`);
            
            // Option 2: Set userId to null (safer option)
            await Group.updateMany(
                { _id: { $in: groupsWithInvalidUsers.map(g => g._id) } },
                { $unset: { userId: 1 } }
            );
            console.log(`🧹 [GROUP CLEANUP] Set userId to null for ${groupsWithInvalidUsers.length} groups with invalid userId references`);
            
            return groupsWithInvalidUsers.length;
        } else {
            console.log(`✅ [GROUP CLEANUP] No groups with invalid userId references found`);
            return 0;
        }
    } catch (error) {
        console.error(`❌ [GROUP CLEANUP ERROR] Failed to cleanup groups:`, error);
        throw error;
    }
};

// Get all groups
exports.getAllGroups = async (req, res) => {
    try {
        const { groupType, page = 1, limit = 20 } = req.query;
        
        console.log(`👥 [GROUP DEBUG] Getting all groups`);
        console.log(`👥 [GROUP DEBUG] Group type filter: ${groupType}`);
        console.log(`👥 [GROUP DEBUG] Page: ${page}, Limit: ${limit}`);
        
        const skip = (parseInt(page) - 1) * parseInt(limit);
        let query = {};
        
        if (groupType) {
            query.groupType = groupType;
        }
        
        const groups = await Group.find(query)
            .populate('userId', 'name mobile')
            .sort({ createdAt: -1 })
            .skip(skip)
            .limit(parseInt(limit));
        
        const totalGroups = await Group.countDocuments(query);
        
        console.log(`📊 [GROUP DEBUG] Found ${groups.length} groups (${totalGroups} total)`);
        
        res.json({
            success: true,
            message: 'Groups retrieved successfully',
            data: {
                groups,
                pagination: {
                    currentPage: parseInt(page),
                    totalPages: Math.ceil(totalGroups / parseInt(limit)),
                    totalGroups,
                    hasNext: parseInt(page) < Math.ceil(totalGroups / parseInt(limit)),
                    hasPrev: parseInt(page) > 1
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [GROUP ERROR] Get all groups failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get groups',
            error: error.message
        });
    }
};

// Get groups by user
exports.getUserGroups = async (req, res) => {
    try {
        const { userId } = req.params;
        const { groupType } = req.query;
        
        console.log(`👥 [GROUP DEBUG] Getting groups for userId: ${userId}`);
        console.log(`👥 [GROUP DEBUG] Group type filter: ${groupType}`);
        
        const groups = await Group.getUserGroups(userId, groupType);
        
        console.log(`📊 [GROUP DEBUG] Found ${groups.length} groups for user`);
        
        res.json({
            success: true,
            message: 'User groups retrieved successfully',
            data: {
                groups,
                totalGroups: groups.length,
                userId
            }
        });
        
    } catch (error) {
        console.error('❌ [GROUP ERROR] Get user groups failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get user groups',
            error: error.message
        });
    }
};

// Get group by ID with complete information
exports.getGroupById = async (req, res) => {
    try {
        const { groupId } = req.params;
        
        console.log(`👥 [GROUP DEBUG] Getting complete group information for ID: ${groupId}`);
        
        const group = await Group.findById(groupId)
            .populate('userId', 'name mobile email profileImage')
            .populate('members.user_id', 'name mobile email profileImage occupation');
        
        if (!group) {
            console.log(`❌ [GROUP DEBUG] Group not found: ${groupId}`);
            return res.status(404).json({
                success: false,
                message: 'Group not found'
            });
        }
        
        console.log(`✅ [GROUP DEBUG] Group found: ${group._id}`);
        console.log(`📊 [GROUP DEBUG] Group has ${group.members ? group.members.length : 0} members`);
        
        // Get recent messages if requested
        const { includeMessages = false, messageLimit = 10 } = req.query;
        let recentMessages = [];
        
        if (includeMessages === 'true') {
            try {
                const GroupMessage = require('../models/GroupMessage');
                recentMessages = await GroupMessage.find({
                    groupId: groupId,
                    isVisible: true,
                    isDeleted: false
                })
                .populate('userId', 'name mobile profileImage')
                .sort({ createdAt: -1 })
                .limit(parseInt(messageLimit));
                
                console.log(`💬 [GROUP DEBUG] Found ${recentMessages.length} recent messages`);
            } catch (messageError) {
                console.log(`⚠️ [GROUP DEBUG] Could not fetch messages: ${messageError.message}`);
            }
        }
        
        // Format the response with complete group information
        const formattedGroup = {
            groupId: group._id,
            groupType: group.groupType,
            groupName: group.groupName,
            description: group.description,
            memberCount: group.memberCount,
            membersCount: group.members ? group.members.length : 0,
            isActive: group.isActive,
            createdAt: group.createdAt,
            updatedAt: group.updatedAt,
            createdBy: {
                userId: group.userId._id,
                name: group.userId.name,
                mobile: group.userId.mobile,
                email: group.userId.email,
                profileImage: group.userId.profileImage
            },
            members: group.members ? group.members.map(member => ({
                user_id: member.user_id._id,
                name: member.name,
                joinDate: member.joinDate,
                role: member.role,
                isActive: member.isActive,
                userDetails: {
                    name: member.user_id.name,
                    mobile: member.user_id.mobile,
                    email: member.user_id.email,
                    profileImage: member.user_id.profileImage,
                    occupation: member.user_id.occupation
                }
            })) : [],
            // Additional group-specific information
            schoolId: group.schoolId,
            collegeId: group.collegeId,
            // Recent messages if requested
            recentMessages: recentMessages
        };
        
        // Calculate statistics
        const statistics = {
            totalMembers: group.members ? group.members.length : 0,
            activeMembers: group.members ? group.members.filter(m => m.isActive).length : 0,
            adminCount: group.members ? group.members.filter(m => m.role === 'admin').length : 0,
            moderatorCount: group.members ? group.members.filter(m => m.role === 'moderator').length : 0,
            regularMemberCount: group.members ? group.members.filter(m => m.role === 'member').length : 0,
            recentMessagesCount: recentMessages.length
        };
        
        res.json({
            success: true,
            message: 'Group information retrieved successfully',
            data: {
                group: formattedGroup,
                statistics: statistics
            }
        });
        
    } catch (error) {
        console.error('❌ [GROUP ERROR] Get group by ID failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get group information',
            error: error.message
        });
    }
};

// Get group by school ID
exports.getGroupBySchoolId = async (req, res) => {
    try {
        const { schoolId } = req.params;
        
        console.log(`🏫 [GROUP DEBUG] Getting group by school ID: ${schoolId}`);
        
        const group = await Group.getGroupBySchoolId(schoolId);
        
        if (!group) {
            console.log(`❌ [GROUP DEBUG] Group not found for school ID: ${schoolId}`);
            return res.status(404).json({
                success: false,
                message: 'Group not found for this school ID'
            });
        }
        
        console.log(`✅ [GROUP DEBUG] Group found: ${group._id}`);
        
        res.json({
            success: true,
            message: 'Group retrieved successfully',
            data: {
                group
            }
        });
        
    } catch (error) {
        console.error('❌ [GROUP ERROR] Get group by school ID failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get group by school ID',
            error: error.message
        });
    }
};

// Get group by college ID
exports.getGroupByCollegeId = async (req, res) => {
    try {
        const { collegeId } = req.params;
        
        console.log(`🎓 [GROUP DEBUG] Getting group by college ID: ${collegeId}`);
        
        const group = await Group.getGroupByCollegeId(collegeId);
        
        if (!group) {
            console.log(`❌ [GROUP DEBUG] Group not found for college ID: ${collegeId}`);
            return res.status(404).json({
                success: false,
                message: 'Group not found for this college ID'
            });
        }
        
        console.log(`✅ [GROUP DEBUG] College group found: ${group._id}`);
        
        res.json({
            success: true,
            message: 'College group retrieved successfully',
            data: {
                group
            }
        });
        
    } catch (error) {
        console.error('❌ [GROUP ERROR] Get group by college ID failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get group by college ID',
            error: error.message
        });
    }
};

// Create group
exports.createGroup = async (req, res) => {
    try {
        const { groupType, userId, schoolId, groupName, description } = req.body;
        
        console.log(`👥 [GROUP DEBUG] Creating group`);
        console.log(`👥 [GROUP DEBUG] Group type: ${groupType}`);
        console.log(`👥 [GROUP DEBUG] User ID: ${userId}`);
        console.log(`👥 [GROUP DEBUG] School ID: ${schoolId}`);
        
        // Validate required fields
        if (!groupType || !userId) {
            return res.status(400).json({
                success: false,
                message: 'Group type and user ID are required'
            });
        }
        
        // Check if user exists
        const user = await User.findById(userId);
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        // For school groups, check if schoolId is provided
        if (groupType === 'school' && !schoolId) {
            return res.status(400).json({
                success: false,
                message: 'School ID is required for school groups'
            });
        }
        
        // Check if school group already exists
        if (groupType === 'school' && schoolId) {
            const existingGroup = await Group.findOne({ 
                groupType: 'school', 
                schoolId: schoolId 
            });
            
            if (existingGroup) {
                console.log(`✅ [GROUP DEBUG] School group already exists: ${existingGroup._id}`);
                return res.json({
                    success: true,
                    message: 'School group already exists',
                    data: {
                        group: existingGroup
                    }
                });
            }
        }
        
        const group = new Group({
            groupType,
            userId,
            schoolId: groupType === 'school' ? schoolId : undefined,
            groupName,
            description,
            memberCount: 1
        });
        
        await group.save();
        
        console.log(`✅ [GROUP DEBUG] Group created: ${group._id}`);
        
        res.status(201).json({
            success: true,
            message: 'Group created successfully',
            data: {
                group
            }
        });
        
    } catch (error) {
        console.error('❌ [GROUP ERROR] Create group failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to create group',
            error: error.message
        });
    }
};

// Update group
exports.updateGroup = async (req, res) => {
    try {
        const { groupId } = req.params;
        const updateData = req.body;
        
        console.log(`👥 [GROUP DEBUG] Updating group: ${groupId}`);
        console.log(`👥 [GROUP DEBUG] Update data:`, updateData);
        
        const group = await Group.findById(groupId);
        
        if (!group) {
            console.log(`❌ [GROUP DEBUG] Group not found: ${groupId}`);
            return res.status(404).json({
                success: false,
                message: 'Group not found'
            });
        }
        
        // Update only allowed fields
        const allowedFields = ['groupName', 'description', 'isActive'];
        Object.keys(updateData).forEach(key => {
            if (allowedFields.includes(key) && updateData[key] !== undefined) {
                group[key] = updateData[key];
                console.log(`👥 [GROUP DEBUG] Updated ${key}: ${updateData[key]}`);
            }
        });
        
        await group.save();
        
        console.log(`✅ [GROUP DEBUG] Group updated: ${group._id}`);
        
        res.json({
            success: true,
            message: 'Group updated successfully',
            data: {
                group
            }
        });
        
    } catch (error) {
        console.error('❌ [GROUP ERROR] Update group failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update group',
            error: error.message
        });
    }
};

// Delete group
exports.deleteGroup = async (req, res) => {
    try {
        const { groupId } = req.params;
        
        console.log(`👥 [GROUP DEBUG] Deleting group: ${groupId}`);
        
        const group = await Group.findById(groupId);
        
        if (!group) {
            console.log(`❌ [GROUP DEBUG] Group not found: ${groupId}`);
            return res.status(404).json({
                success: false,
                message: 'Group not found'
            });
        }
        
        await Group.findByIdAndDelete(groupId);
        
        console.log(`✅ [GROUP DEBUG] Group deleted: ${groupId}`);
        
        res.json({
            success: true,
            message: 'Group deleted successfully'
        });
        
    } catch (error) {
        console.error('❌ [GROUP ERROR] Delete group failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to delete group',
            error: error.message
        });
    }
};

// Get all groups by user ID (from user's group IDs) with member checking
exports.getUserGroupsById = async (req, res) => {
    try {
        const { userId } = req.params;
        
        console.log(`👥 [USER GROUPS DEBUG] Getting all groups for userId: ${userId}`);
        
        // Find user to get their group IDs
        const user = await User.findById(userId).select('schoolGroupId collegeGroupId professionalGroupId name mobile');
        
        if (!user) {
            console.log(`❌ [USER GROUPS DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        console.log(`👥 [USER GROUPS DEBUG] User found:`, {
            userId: user._id,
            name: user.name,
            schoolGroupId: user.schoolGroupId,
            collegeGroupId: user.collegeGroupId,
            professionalGroupId: user.professionalGroupId
        });
        
        // Collect all group IDs
        const groupIds = [];
        if (user.schoolGroupId) groupIds.push(user.schoolGroupId);
        if (user.collegeGroupId) groupIds.push(user.collegeGroupId);
        if (user.professionalGroupId) groupIds.push(user.professionalGroupId);
        
        console.log(`👥 [USER GROUPS DEBUG] Group IDs to fetch:`, groupIds);
        
        if (groupIds.length === 0) {
            console.log(`👥 [USER GROUPS DEBUG] No groups found for user`);
            return res.json({
                success: true,
                message: 'No groups found for user',
                data: {
                    user: {
                        userId: user._id,
                        name: user.name,
                        mobile: user.mobile,
                        schoolGroupId: user.schoolGroupId,
                        collegeGroupId: user.collegeGroupId,
                        professionalGroupId: user.professionalGroupId
                    },
                    groups: [],
                    totalGroups: 0
                }
            });
        }
        
        // First, get groups without population to check original userId values
        const groupsWithoutPopulate = await Group.find({ _id: { $in: groupIds } })
            .select('_id userId groupName groupType')
            .sort({ createdAt: -1 });
        
        // Check for groups with null or invalid userId before population
        const groupsWithInvalidUserId = groupsWithoutPopulate.filter(group => !group.userId);
        if (groupsWithInvalidUserId.length > 0) {
            console.log(`⚠️ [USER GROUPS DEBUG] Found ${groupsWithInvalidUserId.length} groups with null/invalid userId:`, 
                groupsWithInvalidUserId.map(g => ({ id: g._id, userId: g.userId, groupName: g.groupName })));
        }
        
        // Now fetch all groups with members populated
        const groups = await Group.find({ _id: { $in: groupIds } })
            .populate('userId', 'name mobile')
            .sort({ createdAt: -1 });
        
        console.log(`📊 [USER GROUPS DEBUG] Found ${groups.length} groups for user`);
        
        // Format response with detailed group information and member checking
        const formattedGroups = groups.map(group => {
            // Check if user is in the members array
            const isUserMember = group.members ? group.members.some(member => 
                member.user_id.toString() === userId.toString()
            ) : false;
            
            console.log(`👥 [USER GROUPS DEBUG] Group ${group._id}: isUserMember = ${isUserMember}`);
            console.log(`👥 [USER GROUPS DEBUG] Group ${group._id}: userId populated = ${!!group.userId}`);
            if (!group.userId) {
                console.log(`⚠️ [USER GROUPS DEBUG] Group ${group._id}: userId is null - group may reference deleted user`);
            }
            
            return {
                groupId: group._id,
                groupType: group.groupType,
                groupName: group.groupName,
                description: group.description,
                memberCount: group.memberCount,
                membersCount: group.members ? group.members.length : 0,
                isUserMember: isUserMember,
                isActive: group.isActive,
                createdBy: group.userId ? {
                    userId: group.userId._id,
                    name: group.userId.name,
                    mobile: group.userId.mobile
                } : {
                    userId: null,
                    name: 'Unknown User',
                    mobile: null
                },
                // Group-specific IDs
                schoolId: group.schoolId,
                collegeId: group.collegeId,
                // Members array (optional - can be removed if not needed)
                members: group.members ? group.members.map(member => ({
                    user_id: member.user_id,
                    name: member.name,
                    joinDate: member.joinDate,
                    role: member.role,
                    isActive: member.isActive,
                    isCurrentUser: member.user_id.toString() === userId.toString()
                })) : [],
                createdAt: group.createdAt,
                updatedAt: group.updatedAt
            };
        });
        
        // Calculate summary statistics
        const summary = {
            totalGroups: formattedGroups.length,
            userIsMemberOf: formattedGroups.filter(g => g.isUserMember).length,
            userIsNotMemberOf: formattedGroups.filter(g => !g.isUserMember).length,
            byType: {
                school: formattedGroups.filter(g => g.groupType === 'school').length,
                college: formattedGroups.filter(g => g.groupType === 'college').length,
                professional: formattedGroups.filter(g => g.groupType === 'professional').length
            }
        };
        
        console.log(`📊 [USER GROUPS DEBUG] Summary:`, summary);
        
        res.json({
            success: true,
            message: 'User groups retrieved successfully',
            data: {
                user: {
                    userId: user._id,
                    name: user.name,
                    mobile: user.mobile,
                    schoolGroupId: user.schoolGroupId,
                    collegeGroupId: user.collegeGroupId,
                    professionalGroupId: user.professionalGroupId
                },
                groups: formattedGroups,
                summary: summary
            }
        });
        
    } catch (error) {
        console.error('❌ [USER GROUPS ERROR] Get user groups failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get user groups',
            error: error.message
        });
    }
};

// Join group - Add user to group's members array
exports.joinGroup = async (req, res) => {
    try {
        const { groupId } = req.params;
        const { userId, role = 'member' } = req.body;
        
        console.log(`👥 [JOIN GROUP DEBUG] User ${userId} joining group ${groupId}`);
        console.log(`👥 [JOIN GROUP DEBUG] Role: ${role}`);
        
        // Validate required fields
        if (!userId) {
            return res.status(400).json({
                success: false,
                message: 'User ID is required'
            });
        }
        
        // Check if user exists
        const user = await User.findById(userId).select('name mobile');
        if (!user) {
            console.log(`❌ [JOIN GROUP DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        // Find the group
        const group = await Group.findById(groupId);
        if (!group) {
            console.log(`❌ [JOIN GROUP DEBUG] Group not found: ${groupId}`);
            return res.status(404).json({
                success: false,
                message: 'Group not found'
            });
        }
        
        // Check if group is active
        if (!group.isActive) {
            console.log(`❌ [JOIN GROUP DEBUG] Group is not active: ${groupId}`);
            return res.status(400).json({
                success: false,
                message: 'Group is not active'
            });
        }
        
        // Check if user is already a member
        const existingMember = group.members ? group.members.find(member => 
            member.user_id.toString() === userId.toString()
        ) : null;
        
        if (existingMember) {
            console.log(`✅ [JOIN GROUP DEBUG] User is already a member of this group`);
            return res.json({
                success: true,
                message: 'User is already a member of this group',
                data: {
                    group: {
                        groupId: group._id,
                        groupName: group.groupName,
                        groupType: group.groupType,
                        memberCount: group.memberCount,
                        membersCount: group.members ? group.members.length : 0
                    },
                    user: {
                        userId: user._id,
                        name: user.name,
                        mobile: user.mobile,
                        role: existingMember.role,
                        joinDate: existingMember.joinDate,
                        isActive: existingMember.isActive
                    },
                    alreadyMember: true
                }
            });
        }
        
        // Add user to members array
        const newMember = {
            user_id: userId,
            name: user.name,
            joinDate: new Date(),
            role: role,
            isActive: true
        };
        
        // Initialize members array if it doesn't exist
        if (!group.members) {
            group.members = [];
        }
        
        group.members.push(newMember);
        group.memberCount = group.members.length;
        
        await group.save();
        
        console.log(`✅ [JOIN GROUP DEBUG] User ${userId} successfully joined group ${groupId}`);
        console.log(`📊 [JOIN GROUP DEBUG] Group now has ${group.memberCount} members`);
        
        // Populate the group with user details for response
        const populatedGroup = await Group.findById(groupId)
            .populate('userId', 'name mobile')
            .populate('members.user_id', 'name mobile email');
        
        res.json({
            success: true,
            message: 'User successfully joined the group',
            data: {
                group: {
                    groupId: populatedGroup._id,
                    groupName: populatedGroup.groupName,
                    groupType: populatedGroup.groupType,
                    description: populatedGroup.description,
                    memberCount: populatedGroup.memberCount,
                    membersCount: populatedGroup.members ? populatedGroup.members.length : 0,
                    isActive: populatedGroup.isActive,
                    createdBy: {
                        userId: populatedGroup.userId._id,
                        name: populatedGroup.userId.name,
                        mobile: populatedGroup.userId.mobile
                    },
                    schoolId: populatedGroup.schoolId,
                    collegeId: populatedGroup.collegeId,
                    createdAt: populatedGroup.createdAt,
                    updatedAt: populatedGroup.updatedAt
                },
                user: {
                    userId: user._id,
                    name: user.name,
                    mobile: user.mobile,
                    role: newMember.role,
                    joinDate: newMember.joinDate,
                    isActive: newMember.isActive
                },
                membership: {
                    totalMembers: populatedGroup.memberCount,
                    userPosition: populatedGroup.members.length, // Position in members array
                    role: newMember.role
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [JOIN GROUP ERROR] Join group failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to join group',
            error: error.message
        });
    }
};

// Leave group - Remove user from group's members array
exports.leaveGroup = async (req, res) => {
    try {
        const { groupId } = req.params;
        const { userId } = req.body;
        
        console.log(`👥 [LEAVE GROUP DEBUG] User ${userId} leaving group ${groupId}`);
        
        // Validate required fields
        if (!userId) {
            return res.status(400).json({
                success: false,
                message: 'User ID is required'
            });
        }
        
        // Check if user exists
        const user = await User.findById(userId).select('name mobile');
        if (!user) {
            console.log(`❌ [LEAVE GROUP DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        // Find the group
        const group = await Group.findById(groupId);
        if (!group) {
            console.log(`❌ [LEAVE GROUP DEBUG] Group not found: ${groupId}`);
            return res.status(404).json({
                success: false,
                message: 'Group not found'
            });
        }
        
        // Check if user is a member
        if (!group.members || group.members.length === 0) {
            console.log(`❌ [LEAVE GROUP DEBUG] User is not a member of this group`);
            return res.status(400).json({
                success: false,
                message: 'User is not a member of this group'
            });
        }
        
        const memberIndex = group.members.findIndex(member => 
            member.user_id.toString() === userId.toString()
        );
        
        if (memberIndex === -1) {
            console.log(`❌ [LEAVE GROUP DEBUG] User is not a member of this group`);
            return res.status(400).json({
                success: false,
                message: 'User is not a member of this group'
            });
        }
        
        // Remove user from members array
        const removedMember = group.members[memberIndex];
        group.members.splice(memberIndex, 1);
        group.memberCount = group.members.length;
        
        await group.save();
        
        console.log(`✅ [LEAVE GROUP DEBUG] User ${userId} successfully left group ${groupId}`);
        console.log(`📊 [LEAVE GROUP DEBUG] Group now has ${group.memberCount} members`);
        
        res.json({
            success: true,
            message: 'User successfully left the group',
            data: {
                group: {
                    groupId: group._id,
                    groupName: group.groupName,
                    groupType: group.groupType,
                    memberCount: group.memberCount,
                    membersCount: group.members.length
                },
                user: {
                    userId: user._id,
                    name: user.name,
                    mobile: user.mobile
                },
                membership: {
                    totalMembers: group.memberCount,
                    removedRole: removedMember.role,
                    removedJoinDate: removedMember.joinDate
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [LEAVE GROUP ERROR] Leave group failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to leave group',
            error: error.message
        });
    }
};

// Demo API - Simple join group with userId and groupId only
exports.demoJoinGroup = async (req, res) => {
    try {
        const { userId, groupId } = req.body;
        
        console.log(`🎯 [DEMO JOIN GROUP] User ${userId} joining group ${groupId}`);
        
        // Validate required fields
        if (!userId || !groupId) {
            return res.status(400).json({
                success: false,
                message: 'User ID and Group ID are required'
            });
        }
        
        // Check if user exists and get user details
        const user = await User.findById(userId).select('name mobile emailId occupation');
        if (!user) {
            console.log(`❌ [DEMO JOIN GROUP] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        console.log(`✅ [DEMO JOIN GROUP] User found:`, {
            userId: user._id,
            name: user.name,
            mobile: user.mobile,
            emailId: user.emailId,
            occupation: user.occupation
        });
        
        // Find the group
        const group = await Group.findById(groupId);
        if (!group) {
            console.log(`❌ [DEMO JOIN GROUP] Group not found: ${groupId}`);
            return res.status(404).json({
                success: false,
                message: 'Group not found'
            });
        }
        
        console.log(`✅ [DEMO JOIN GROUP] Group found:`, {
            groupId: group._id,
            groupName: group.groupName,
            groupType: group.groupType,
            memberCount: group.memberCount,
            membersCount: group.members ? group.members.length : 0
        });
        
        // Check if group is active
        if (!group.isActive) {
            console.log(`❌ [DEMO JOIN GROUP] Group is not active: ${groupId}`);
            return res.status(400).json({
                success: false,
                message: 'Group is not active'
            });
        }
        
        // Check if user is already a member
        const existingMember = group.members ? group.members.find(member => 
            member.user_id.toString() === userId.toString()
        ) : null;
        
        if (existingMember) {
            console.log(`✅ [DEMO JOIN GROUP] User is already a member of this group`);
            return res.json({
                success: true,
                message: 'User is already a member of this group',
                data: {
                    group: {
                        groupId: group._id,
                        groupName: group.groupName,
                        groupType: group.groupType,
                        memberCount: group.memberCount,
                        membersCount: group.members ? group.members.length : 0,
                        schoolId: group.schoolId,
                        collegeId: group.collegeId
                    },
                    user: {
                        userId: user._id,
                        name: user.name,
                        mobile: user.mobile,
                        emailId: user.emailId,
                        occupation: user.occupation,
                        role: existingMember.role,
                        joinDate: existingMember.joinDate,
                        isActive: existingMember.isActive
                    },
                    alreadyMember: true
                }
            });
        }
        
        // Create new member object exactly as the Group model expects
        const newMember = {
            user_id: userId,                    // ObjectId reference to User
            name: user.name,                    // User's name from User model
            joinDate: new Date(),               // Current date
            role: 'member',                     // Default role
            isActive: true                      // Active status
        };
        
        console.log(`👥 [DEMO JOIN GROUP] Adding new member:`, newMember);
        
        // Initialize members array if it doesn't exist
        if (!group.members) {
            group.members = [];
        }
        
        // Add user to members array
        group.members.push(newMember);
        
        // Update member count
        group.memberCount = group.members.length;
        
        // Save the group
        await group.save();
        
        console.log(`✅ [DEMO JOIN GROUP] User ${userId} successfully joined group ${groupId}`);
        console.log(`📊 [DEMO JOIN GROUP] Group now has ${group.memberCount} members`);
        
        // Return success response with complete details
        res.json({
            success: true,
            message: 'User successfully joined the group',
            data: {
                group: {
                    groupId: group._id,
                    groupName: group.groupName,
                    groupType: group.groupType,
                    description: group.description,
                    memberCount: group.memberCount,
                    membersCount: group.members.length,
                    isActive: group.isActive,
                    schoolId: group.schoolId,
                    collegeId: group.collegeId,
                    createdAt: group.createdAt,
                    updatedAt: group.updatedAt
                },
                user: {
                    userId: user._id,
                    name: user.name,
                    mobile: user.mobile,
                    emailId: user.emailId,
                    occupation: user.occupation,
                    role: newMember.role,
                    joinDate: newMember.joinDate,
                    isActive: newMember.isActive
                },
                membership: {
                    totalMembers: group.memberCount,
                    userPosition: group.members.length,
                    role: newMember.role,
                    joinDate: newMember.joinDate
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [DEMO JOIN GROUP ERROR] Demo join group failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to join group',
            error: error.message
        });
    }
};

// Find or create school group (for school details update)
exports.findOrCreateSchoolGroup = async (req, res) => {
    try {
        const { userId, schoolId, schoolDetails } = req.body;
        
        console.log(`🏫 [GROUP DEBUG] Finding or creating school group`);
        console.log(`🏫 [GROUP DEBUG] User ID: ${userId}`);
        console.log(`🏫 [GROUP DEBUG] School ID: ${schoolId}`);
        
        if (!userId || !schoolId || !schoolDetails) {
            return res.status(400).json({
                success: false,
                message: 'User ID, school ID, and school details are required'
            });
        }
        
        const group = await Group.findOrCreateSchoolGroup(userId, schoolId, schoolDetails);
        
        console.log(`✅ [GROUP DEBUG] School group processed: ${group._id}`);
        
        res.json({
            success: true,
            message: 'School group processed successfully',
            data: {
                group
            }
        });
        
    } catch (error) {
        console.error('❌ [GROUP ERROR] Find or create school group failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to process school group',
            error: error.message
        });
    }
};
