const express = require('express');
const router = express.Router();
const User = require('../models/User');
const Follower = require('../models/Follower');
const Notification = require('../models/Notification');
const { authenticateToken } = require('../middleware/auth');

// @route   GET /api/followers/suggested/:userId
// @desc    Get suggested followers for a user based on interests, school, college, native place, etc.
// @access  Private
router.get('/suggested/:userId', authenticateToken, async (req, res) => {
    try {
        const { userId } = req.params;
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Starting request for user: ${userId}`);
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] No limit restriction - returning all available suggestions`);
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Query params:`, req.query);
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Auth user:`, req.user._id);
        
        // Get the requesting user's details
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Fetching user details...`);
        const user = await User.findById(userId);
        if (!user) {
            console.log(`❌ [SUGGESTED FOLLOWERS DEBUG] User not found: ${userId}`);
            return res.status(404).json({ 
                success: false, 
                message: 'User not found' 
            });
        }
        
        console.log(`✅ [SUGGESTED FOLLOWERS DEBUG] User found:`, {
            id: user._id,
            name: user.name,
            gender: user.gender,
            interests: user.interests,
            schoolCode: user.schoolDetails?.schoolCode,
            collegeCode: user.collegeDetails?.collegeCode,
            nativePlace: user.nativePlace,
            state: user.state,
            pincodeNative: user.pincodeNative
        });
        
        // Get users that the current user already follows or has requested to follow (bidirectional check)
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Checking existing follows...`);
        const existingFollows = await Follower.find({
            $or: [
                { followerId: userId },      // Users current user is following/requested
                { followingId: userId }      // Users following/requested current user
            ]
        });
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Found ${existingFollows.length} existing follow relationships`);
        
        // Debug: Show follow request details
        existingFollows.forEach((follow, index) => {
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Follow ${index + 1}:`, {
                id: follow._id,
                followerId: follow.followerId,
                followingId: follow.followingId,
                status: follow.status,
                message: follow.message
            });
        });
        
        const excludeIds = new Set();
        excludeIds.add(userId.toString()); // Exclude self
        
        // Exclude users with ANY follow relationship (requested, accepted, rejected)
        // This ensures users with pending requests don't appear in suggestions again
        existingFollows.forEach(follow => {
            excludeIds.add(follow.followerId.toString());
            excludeIds.add(follow.followingId.toString());
            
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Excluding user due to ${follow.status} relationship:`, {
                followerId: follow.followerId.toString(),
                followingId: follow.followingId.toString(),
                status: follow.status,
                message: follow.message
            });
        });
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Excluding ${excludeIds.size} users (self + existing follows)`);
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Excluded user IDs:`, Array.from(excludeIds));
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Requesting user ID: ${userId}`);
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Is requesting user in excluded list:`, excludeIds.has(userId.toString()));
        
        // Count different types of relationships for debugging
        const requestedByUser = existingFollows.filter(f => f.followerId.toString() === userId.toString() && f.status === 'requested').length;
        const requestedToUser = existingFollows.filter(f => f.followingId.toString() === userId.toString() && f.status === 'requested').length;
        const acceptedByUser = existingFollows.filter(f => f.followerId.toString() === userId.toString() && f.status === 'accepted').length;
        const acceptedToUser = existingFollows.filter(f => f.followingId.toString() === userId.toString() && f.status === 'accepted').length;
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Follow relationship breakdown:`);
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] - Requested by user: ${requestedByUser}`);
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] - Requested to user: ${requestedToUser}`);
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] - Accepted by user: ${acceptedByUser}`);
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] - Accepted to user: ${acceptedToUser}`);
        
        // Build match criteria based on user's profile
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Building match criteria...`);
        const matchCriteria = {
            _id: { $nin: Array.from(excludeIds) }
            // Removed isVerified restriction to include all users
        };
        
        // Add matching conditions based on user's profile
        const matchConditions = [];
        
        // Match by interests
        if (user.interests && user.interests.length > 0) {
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Adding interests match:`, user.interests);
            matchConditions.push({
                interests: { $in: user.interests }
            });
        }
        
        // Match by school code
        if (user.schoolDetails && user.schoolDetails.schoolCode) {
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Adding school code match:`, user.schoolDetails.schoolCode);
            matchConditions.push({
                'schoolDetails.schoolCode': user.schoolDetails.schoolCode
            });
        }
        
        // Match by college code
        if (user.collegeDetails && user.collegeDetails.collegeCode) {
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Adding college code match:`, user.collegeDetails.collegeCode);
            matchConditions.push({
                'collegeDetails.collegeCode': user.collegeDetails.collegeCode
            });
        }
        
        // Match by native place
        if (user.nativePlace) {
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Adding native place match:`, user.nativePlace);
            matchConditions.push({
                nativePlace: { $regex: new RegExp(user.nativePlace, 'i') }
            });
        }
        
        // Match by pincode (exact match)
        if (user.pincodeNative) {
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Adding pincode match:`, user.pincodeNative);
            matchConditions.push({
                pincodeNative: user.pincodeNative
            });
        }
        
        // Match by state (exact match - but use state name instead of code)
        if (user.state) {
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Adding state match:`, user.state);
            matchConditions.push({
                state: user.state
            });
        }
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Total match conditions: ${matchConditions.length}`);
        
        // If we have match conditions, add them to the main criteria
        if (matchConditions.length > 0) {
            matchCriteria.$or = matchConditions;
        }
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Final match criteria:`, JSON.stringify(matchCriteria, null, 2));
        
        // Get suggested users with scoring
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Querying database for matching users...`);
        let suggestedUsers = await User.find(matchCriteria)
            .select('name profileImage about interests schoolDetails collegeDetails nativePlace state pincodeNative gender');
            // No limit - get all matching users
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Found ${suggestedUsers.length} matching users from database`);
        
        // Debug: Show sample of found users and check for self-inclusion
        if (suggestedUsers.length > 0) {
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Sample of found users:`, suggestedUsers.slice(0, 3).map(u => ({
                id: u._id,
                name: u.name,
                gender: u.gender,
                schoolCode: u.schoolDetails?.schoolCode,
                collegeCode: u.collegeDetails?.collegeCode,
                nativePlace: u.nativePlace,
                state: u.state,
                pincodeNative: u.pincodeNative,
                isVerified: u.isVerified
            })));
            
            // Check if requesting user is included in results
            const selfIncluded = suggestedUsers.some(u => u._id.toString() === userId.toString());
            if (selfIncluded) {
                console.log(`❌ [SUGGESTED FOLLOWERS DEBUG] ERROR: Requesting user found in results! This should not happen.`);
                console.log(`❌ [SUGGESTED FOLLOWERS DEBUG] Requesting user ID: ${userId}`);
                console.log(`❌ [SUGGESTED FOLLOWERS DEBUG] Excluded IDs:`, Array.from(excludeIds));
            } else {
                console.log(`✅ [SUGGESTED FOLLOWERS DEBUG] Requesting user correctly excluded from results`);
            }
        }
        
        // Special case: If no users found at all, check if there are any users in the database
        if (suggestedUsers.length === 0) {
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] No matching users found. Checking total users in database...`);
            const totalUsersCount = await User.countDocuments();
            const verifiedUsersCount = await User.countDocuments({ isVerified: true });
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Total users in database: ${totalUsersCount}`);
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Total verified users in database: ${verifiedUsersCount}`);
            
            if (totalUsersCount === 0) {
                console.log(`⚠️ [SUGGESTED FOLLOWERS DEBUG] No users found in database. Returning empty response.`);
                return res.json({
                    success: true,
                    data: [],
                    total: 0,
                    debug: {
                        matchedUsers: 0,
                        additionalRandomUsers: 0,
                        totalUsersInDatabase: 0,
                        message: "No users found in database"
                    }
                });
            }
            
            // If there are users but no matches, we'll continue to add random users below
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Found ${totalUsersCount} users in database, will add random suggestions`);
        }
        
        // Score and rank users based on match criteria
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Scoring and ranking users...`);
        const scoredUsers = suggestedUsers.map(suggestedUser => {
            let score = 0;
            let matchReasons = [];
            
            // Interest matching (highest weight)
            if (user.interests && suggestedUser.interests) {
                const commonInterests = user.interests.filter(interest => 
                    suggestedUser.interests.includes(interest)
                );
                if (commonInterests.length > 0) {
                    score += commonInterests.length * 10;
                    matchReasons.push(`${commonInterests.length} common interest${commonInterests.length > 1 ? 's' : ''}: ${commonInterests.join(', ')}`);
                }
            }
            
            // School code matching (high weight)
            if (user.schoolDetails?.schoolCode && 
                suggestedUser.schoolDetails?.schoolCode && 
                user.schoolDetails.schoolCode === suggestedUser.schoolDetails.schoolCode) {
                score += 15;
                matchReasons.push(`Same school: ${user.schoolDetails.schoolName || 'School'}`);
            }
            
            // College code matching (high weight)
            if (user.collegeDetails?.collegeCode && 
                suggestedUser.collegeDetails?.collegeCode && 
                user.collegeDetails.collegeCode === suggestedUser.collegeDetails.collegeCode) {
                score += 15;
                matchReasons.push(`Same college: ${user.collegeDetails.collegeName || 'College'}`);
            }
            
            // Native place matching (medium weight)
            if (user.nativePlace && suggestedUser.nativePlace && 
                user.nativePlace.toLowerCase() === suggestedUser.nativePlace.toLowerCase()) {
                score += 8;
                matchReasons.push(`Same native place: ${user.nativePlace}`);
            }
            
            // Same pincode and state (medium weight)
            if (user.pincodeNative && suggestedUser.pincodeNative && 
                user.state && suggestedUser.state &&
                user.pincodeNative === suggestedUser.pincodeNative && 
                user.state === suggestedUser.state) {
                score += 12;
                matchReasons.push(`Same location`);
            } else if (user.state && suggestedUser.state && 
                      user.state === suggestedUser.state) {
                score += 5;
                matchReasons.push(`Same location`);
            }
            
            return {
                ...suggestedUser.toObject(),
                matchScore: score,
                matchReasons: matchReasons
            };
        });
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Scored ${scoredUsers.length} users`);
        
        // Sort by match score and get all suggestions with scores > 0
        const topSuggestions = scoredUsers
            .filter(user => user.matchScore > 0)
            .sort((a, b) => b.matchScore - a.matchScore);
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Top suggestions with scores > 0: ${topSuggestions.length}`);
        
        // Get mutual friends and follow status for each suggestion
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Getting mutual friends and follow status for ${topSuggestions.length} suggestions...`);
        const suggestionsWithMutualFriends = await Promise.all(
            topSuggestions.map(async (suggestion) => {
                try {
                    const mutualFriends = await Follower.getMutualFriends(userId, suggestion._id);
                    
                    // Get follow status between current user and suggested user
                    const followStatus = await Follower.findOne({
                        $or: [
                            { followerId: userId, followingId: suggestion._id },
                            { followerId: suggestion._id, followingId: userId }
                        ]
                    });
                    
                    let followRelationship = 'none';
                    let canFollow = true;
                    
                    if (followStatus) {
                        if (followStatus.followerId.toString() === userId.toString()) {
                            // Current user is the follower
                            followRelationship = followStatus.status; // 'requested', 'accepted', 'rejected'
                            canFollow = followStatus.status === 'rejected'; // Can follow again if rejected
                        } else {
                            // Suggested user is the follower
                            followRelationship = followStatus.status; // 'requested', 'accepted', 'rejected'
                            canFollow = false; // Can't follow someone who's following you
                        }
                    }
                    
                    console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] User ${suggestion._id} follow status:`, {
                        followRelationship,
                        canFollow,
                        followStatusId: followStatus?._id
                    });
                    
                    return {
                        ...suggestion,
                        mutualFriendsCount: mutualFriends.length,
                        mutualFriends: mutualFriends.slice(0, 5), // Limit to 5 mutual friends
                        followRelationship,
                        canFollow
                    };
                } catch (error) {
                    console.error('Error getting mutual friends:', error);
                    return {
                        ...suggestion,
                        mutualFriendsCount: 0,
                        mutualFriends: [],
                        followRelationship: 'none',
                        canFollow: true
                    };
                }
            })
        );
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Processed ${suggestionsWithMutualFriends.length} suggestions with mutual friends`);
        
        // Always add random users based on gender to provide more suggestions
        const usedIds = new Set(suggestionsWithMutualFriends.map(s => s._id.toString()));
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Adding random users to provide more suggestions...`);
        
        let additionalUsers = [];
        
        // Get opposite gender users if user has gender specified
        if (user.gender) {
            const oppositeGender = user.gender === 'Male' ? 'Female' : user.gender === 'Female' ? 'Male' : null;
            
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] User gender: ${user.gender}, looking for opposite: ${oppositeGender}`);
            
            if (oppositeGender) {
                console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Querying opposite gender users with exclusion list:`, Array.from(usedIds));
                
                const oppositeGenderUsers = await User.find({
                    _id: { $nin: Array.from(usedIds) },
                    gender: oppositeGender
                })
                .select('name profileImage about interests schoolDetails collegeDetails nativePlace state pincodeNative gender isVerified');
                
                console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Found ${oppositeGenderUsers.length} opposite gender users`);
                if (oppositeGenderUsers.length > 0) {
                    console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Sample opposite gender users:`, oppositeGenderUsers.slice(0, 2).map(u => ({
                        id: u._id,
                        name: u.name,
                        gender: u.gender,
                        isVerified: u.isVerified
                    })));
                }
                additionalUsers.push(...oppositeGenderUsers);
            }
        }
        
        // Get same gender users
        const sameGenderCriteria = user.gender ? { gender: user.gender } : {};
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Looking for same gender users with criteria:`, sameGenderCriteria);
        
        const sameGenderUsers = await User.find({
            _id: { $nin: Array.from(usedIds) },
            ...sameGenderCriteria
        })
        .select('name profileImage about interests schoolDetails collegeDetails nativePlace state pincodeNative gender isVerified');
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Found ${sameGenderUsers.length} same gender users`);
        additionalUsers.push(...sameGenderUsers);
        
        // Get any remaining users not already included
        const currentUsedIds = new Set([
            ...usedIds,
            ...additionalUsers.map(u => u._id.toString())
        ]);
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Getting any remaining users...`);
        
        const remainingUsers = await User.find({
            _id: { $nin: Array.from(currentUsedIds) }
        })
        .select('name profileImage about interests schoolDetails collegeDetails nativePlace state pincodeNative gender isVerified');
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Found ${remainingUsers.length} remaining users`);
        additionalUsers.push(...remainingUsers);
        
        // If still no users found, get any random users from database (last resort)
        if (additionalUsers.length === 0) {
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] No users found in any category. Getting any random users as last resort...`);
            const anyUsers = await User.find({
                _id: { $nin: Array.from(excludeIds) }
            })
            .select('name profileImage about interests schoolDetails collegeDetails nativePlace state pincodeNative gender isVerified');
            
            console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Found ${anyUsers.length} random users as last resort`);
            additionalUsers.push(...anyUsers);
        }
        
        // Shuffle the additional users for randomness
        additionalUsers = additionalUsers.sort(() => Math.random() - 0.5);
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Processing ${additionalUsers.length} additional users with mutual friends...`);
        
        const additionalWithMutual = await Promise.all(
            additionalUsers.map(async (suggestedUser) => {
                try {
                    const mutualFriends = await Follower.getMutualFriends(userId, suggestedUser._id);
                    const genderMatch = suggestedUser.gender === user.gender ? 'Same gender' : 'Different gender';
                    
                    // Get follow status between current user and suggested user
                    const followStatus = await Follower.findOne({
                        $or: [
                            { followerId: userId, followingId: suggestedUser._id },
                            { followerId: suggestedUser._id, followingId: userId }
                        ]
                    });
                    
                    let followRelationship = 'none';
                    let canFollow = true;
                    
                    if (followStatus) {
                        if (followStatus.followerId.toString() === userId.toString()) {
                            // Current user is the follower
                            followRelationship = followStatus.status; // 'requested', 'accepted', 'rejected'
                            canFollow = followStatus.status === 'rejected'; // Can follow again if rejected
                        } else {
                            // Suggested user is the follower
                            followRelationship = followStatus.status; // 'requested', 'accepted', 'rejected'
                            canFollow = false; // Can't follow someone who's following you
                        }
                    }
                    
                    console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Additional user ${suggestedUser._id} follow status:`, {
                        followRelationship,
                        canFollow,
                        followStatusId: followStatus?._id
                    });
                    
                    return {
                        ...suggestedUser.toObject(),
                        matchScore: 0,
                        matchReasons: [`Random suggestion (${genderMatch})`],
                        mutualFriendsCount: mutualFriends.length,
                        mutualFriends: mutualFriends.slice(0, 5),
                        followRelationship,
                        canFollow
                    };
                } catch (error) {
                    const genderMatch = suggestedUser.gender === user.gender ? 'Same gender' : 'Different gender';
                    
                    return {
                        ...suggestedUser.toObject(),
                        matchScore: 0,
                        matchReasons: [`Random suggestion (${genderMatch})`],
                        mutualFriendsCount: 0,
                        mutualFriends: [],
                        followRelationship: 'none',
                        canFollow: true
                    };
                }
            })
        );
        
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Added ${additionalWithMutual.length} additional suggestions`);
        suggestionsWithMutualFriends.push(...additionalWithMutual);
        
        // Generate profile image URLs and final self-exclusion check
        console.log(`🔍 [SUGGESTED FOLLOWERS DEBUG] Generating profile image URLs and checking for self-inclusion...`);
        const finalSuggestions = suggestionsWithMutualFriends.map(user => {
            const profileImageUrl = user.profileImage 
                ? `http://135.181.103.182:5500/uploads/profiles/${user.profileImage}`
                : null;
            
            return {
                ...user,
                profileImageUrl
            };
        });
        
        // Final check: Ensure requesting user is not in final suggestions
        const finalSelfCheck = finalSuggestions.some(u => u._id.toString() === userId.toString());
        if (finalSelfCheck) {
            console.log(`❌ [SUGGESTED FOLLOWERS DEBUG] CRITICAL ERROR: Requesting user found in final suggestions!`);
            console.log(`❌ [SUGGESTED FOLLOWERS DEBUG] Requesting user ID: ${userId}`);
            console.log(`❌ [SUGGESTED FOLLOWERS DEBUG] Final suggestions count: ${finalSuggestions.length}`);
            
            // Remove self from final suggestions as emergency fix
            const filteredSuggestions = finalSuggestions.filter(u => u._id.toString() !== userId.toString());
            console.log(`🔧 [SUGGESTED FOLLOWERS DEBUG] Emergency fix: Removed self, final count: ${filteredSuggestions.length}`);
            finalSuggestions.length = 0;
            finalSuggestions.push(...filteredSuggestions);
        } else {
            console.log(`✅ [SUGGESTED FOLLOWERS DEBUG] Final suggestions correctly exclude requesting user`);
        }
        
        // Additional check: Ensure no users with "requested" status are in suggestions
        const usersWithRequestedStatus = finalSuggestions.filter(u => u.followRelationship === 'requested');
        if (usersWithRequestedStatus.length > 0) {
            console.log(`❌ [SUGGESTED FOLLOWERS DEBUG] ERROR: Found ${usersWithRequestedStatus.length} users with 'requested' status in suggestions!`);
            console.log(`❌ [SUGGESTED FOLLOWERS DEBUG] Users with requested status:`, usersWithRequestedStatus.map(u => ({
                id: u._id,
                name: u.name,
                followRelationship: u.followRelationship
            })));
            
            // Remove users with requested status as emergency fix
            const filteredSuggestions = finalSuggestions.filter(u => u.followRelationship !== 'requested');
            console.log(`🔧 [SUGGESTED FOLLOWERS DEBUG] Emergency fix: Removed ${usersWithRequestedStatus.length} users with requested status, final count: ${filteredSuggestions.length}`);
            finalSuggestions.length = 0;
            finalSuggestions.push(...filteredSuggestions);
        } else {
            console.log(`✅ [SUGGESTED FOLLOWERS DEBUG] No users with 'requested' status found in final suggestions`);
        }
        
        // Final response logging
        console.log(`✅ [SUGGESTED FOLLOWERS DEBUG] Final response prepared:`);
        console.log(`✅ [SUGGESTED FOLLOWERS DEBUG] Total suggestions: ${finalSuggestions.length}`);
        console.log(`✅ [SUGGESTED FOLLOWERS DEBUG] No limit - returning all available suggestions`);
        console.log(`✅ [SUGGESTED FOLLOWERS DEBUG] Response data sample:`, {
            count: finalSuggestions.length,
            firstUser: finalSuggestions[0] ? {
                id: finalSuggestions[0]._id,
                name: finalSuggestions[0].name,
                gender: finalSuggestions[0].gender,
                matchScore: finalSuggestions[0].matchScore,
                matchReasons: finalSuggestions[0].matchReasons
            } : null
        });
        
        // Always return a response, even if empty
        const response = {
            success: true,
            data: finalSuggestions,
            total: finalSuggestions.length,
            debug: {
                matchedUsers: topSuggestions.length,
                additionalRandomUsers: finalSuggestions.length - topSuggestions.length,
                userProfile: {
                    gender: user.gender,
                    hasInterests: user.interests && user.interests.length > 0,
                    hasSchoolCode: user.schoolDetails?.schoolCode ? true : false,
                    hasCollegeCode: user.collegeDetails?.collegeCode ? true : false,
                    hasNativePlace: user.nativePlace ? true : false,
                    hasLocation: user.state ? true : false
                },
                followStatusBreakdown: {
                    requestedByUser: requestedByUser,
                    requestedToUser: requestedToUser,
                    acceptedByUser: acceptedByUser,
                    acceptedToUser: acceptedToUser,
                    totalExcluded: excludeIds.size
                }
            }
        };
        
        console.log(`✅ [SUGGESTED FOLLOWERS DEBUG] Sending response with ${response.data.length} suggestions`);
        console.log(`✅ [SUGGESTED FOLLOWERS DEBUG] Final suggestions user IDs:`, response.data.map(u => u._id.toString()));
        res.json(response);
        
    } catch (error) {
        console.error('❌ [SUGGESTED FOLLOWERS ERROR] Error getting suggested followers:', error);
        console.error('❌ [SUGGESTED FOLLOWERS ERROR] Error stack:', error.stack);
        res.status(500).json({
            success: false,
            message: 'Error getting suggested followers',
            error: error.message,
            debug: {
                userId: req.params.userId,
                timestamp: new Date().toISOString()
            }
        });
    }
});

// @route   POST /api/followers/follow
// @desc    Send a follow request to another user
// @access  Private
router.post('/follow', authenticateToken, async (req, res) => {
    try {
        const { followingId, message } = req.body;
        const followerId = req.user._id; // Auth middleware sets req.user as the full user object
        
        // Check if user is trying to follow themselves
        if (followerId === followingId) {
            return res.status(400).json({
                success: false,
                message: 'You cannot follow yourself'
            });
        }
        
        // Check if follow relationship already exists
        const existingFollow = await Follower.findOne({
            followerId: followerId,
            followingId: followingId
        });
        
        if (existingFollow) {
            return res.status(400).json({
                success: false,
                message: `You have already ${existingFollow.status} this user`
            });
        }
        
        // Create new follow request
        const newFollow = new Follower({
            followerId: followerId,
            followingId: followingId,
            status: 'requested',
            message: message
        });
        
        await newFollow.save();
        
        // Create notification for the user being followed
        try {
            await Notification.createFollowRequestNotification(
                followerId,
                followingId,
                newFollow._id
            );
            console.log(`📢 [FOLLOW REQUEST] Notification created for user ${followingId}`);
        } catch (notificationError) {
            console.error('❌ [FOLLOW REQUEST] Error creating notification:', notificationError);
            // Don't fail the request if notification creation fails
        }
        
        // Populate user details for response
        await newFollow.populate('followingId', 'name profileImage');
        
        res.status(201).json({
            success: true,
            message: 'Follow request sent successfully',
            data: newFollow
        });
        
    } catch (error) {
        console.error('Error sending follow request:', error);
        res.status(500).json({
            success: false,
            message: 'Error sending follow request',
            error: error.message
        });
    }
});

// @route   PUT /api/followers/:followId/status
// @desc    Accept or reject a follow request
// @access  Private
router.put('/:followId/status', authenticateToken, async (req, res) => {
    try {
        const { followId } = req.params;
        const { status } = req.body; // 'accepted' or 'rejected'
        const userId = req.user._id;
        
        if (!['accepted', 'rejected'].includes(status)) {
            return res.status(400).json({
                success: false,
                message: 'Status must be either "accepted" or "rejected"'
            });
        }
        
        const follow = await Follower.findOne({
            _id: followId,
            followingId: userId, // User can only respond to requests sent to them
            status: 'requested'
        });
        
        if (!follow) {
            return res.status(404).json({
                success: false,
                message: 'Follow request not found or already responded to'
            });
        }
        
        // Update status and response time
        follow.status = status;
        follow.respondedAt = new Date();
        await follow.save();
        
        // Create notification for the user who sent the request
        try {
            if (status === 'accepted') {
                await Notification.createFollowAcceptedNotification(
                    follow.followerId,
                    follow.followingId,
                    follow._id
                );
                console.log(`📢 [FOLLOW ACCEPTED] Notification created for user ${follow.followerId}`);
            } else if (status === 'rejected') {
                await Notification.createFollowDeclinedNotification(
                    follow.followerId,
                    follow.followingId,
                    follow._id
                );
                console.log(`📢 [FOLLOW DECLINED] Notification created for user ${follow.followerId}`);
            }
        } catch (notificationError) {
            console.error('❌ [FOLLOW STATUS UPDATE] Error creating notification:', notificationError);
            // Don't fail the request if notification creation fails
        }
        
        // Populate user details for response
        await follow.populate('followerId', 'name profileImage');
        
        res.json({
            success: true,
            message: `Follow request ${status} successfully`,
            data: follow
        });
        
    } catch (error) {
        console.error('Error updating follow status:', error);
        res.status(500).json({
            success: false,
            message: 'Error updating follow status',
            error: error.message
        });
    }
});

// @route   DELETE /api/followers/:followId
// @desc    Unfollow a user or cancel follow request
// @access  Private
router.delete('/:followId', authenticateToken, async (req, res) => {
    try {
        const { followId } = req.params;
        const userId = req.user._id;
        
        const follow = await Follower.findOne({
            _id: followId,
            followerId: userId // User can only unfollow from their own follow requests
        });
        
        if (!follow) {
            return res.status(404).json({
                success: false,
                message: 'Follow relationship not found'
            });
        }
        
        await Follower.findByIdAndDelete(followId);
        
        res.json({
            success: true,
            message: 'Unfollowed successfully'
        });
        
    } catch (error) {
        console.error('Error unfollowing:', error);
        res.status(500).json({
            success: false,
            message: 'Error unfollowing',
            error: error.message
        });
    }
});

// @route   GET /api/followers/:userId/followers
// @desc    Get followers of a user
// @access  Private
router.get('/:userId/followers', authenticateToken, async (req, res) => {
    try {
        const { userId } = req.params;
        const { status = 'accepted' } = req.query;
        
        const followers = await Follower.getFollowers(userId, status);
        
        res.json({
            success: true,
            data: followers,
            total: followers.length
        });
        
    } catch (error) {
        console.error('Error getting followers:', error);
        res.status(500).json({
            success: false,
            message: 'Error getting followers',
            error: error.message
        });
    }
});

// @route   GET /api/followers/:userId/following
// @desc    Get users that a user is following
// @access  Private
router.get('/:userId/following', authenticateToken, async (req, res) => {
    try {
        const { userId } = req.params;
        const { status = 'accepted' } = req.query;
        
        const following = await Follower.getFollowing(userId, status);
        
        res.json({
            success: true,
            data: following,
            total: following.length
        });
        
    } catch (error) {
        console.error('Error getting following:', error);
        res.status(500).json({
            success: false,
            message: 'Error getting following',
            error: error.message
        });
    }
});

// @route   GET /api/followers/:userId/requests
// @desc    Get follow requests for a user
// @access  Private
router.get('/:userId/requests', authenticateToken, async (req, res) => {
    try {
        const { userId } = req.params;
        
        // Ensure user can only see their own requests
        if (req.user._id.toString() !== userId) {
            return res.status(403).json({
                success: false,
                message: 'You can only view your own follow requests'
            });
        }
        
        const requests = await Follower.getFollowRequests(userId);
        
        res.json({
            success: true,
            data: requests,
            total: requests.length
        });
        
    } catch (error) {
        console.error('Error getting follow requests:', error);
        res.status(500).json({
            success: false,
            message: 'Error getting follow requests',
            error: error.message
        });
    }
});

// @route   GET /api/followers/:userId1/:userId2/status
// @desc    Check follow status between two users
// @access  Private
router.get('/:userId1/:userId2/status', authenticateToken, async (req, res) => {
    try {
        const { userId1, userId2 } = req.params;
        
        const status = await Follower.isFollowing(userId1, userId2);
        
        res.json({
            success: true,
            data: {
                followerId: userId1,
                followingId: userId2,
                status: status
            }
        });
        
    } catch (error) {
        console.error('Error checking follow status:', error);
        res.status(500).json({
            success: false,
            message: 'Error checking follow status',
            error: error.message
        });
    }
});

// @route   GET /api/followers/:userId1/:userId2/mutual
// @desc    Get mutual friends between two users
// @access  Private
router.get('/:userId1/:userId2/mutual', authenticateToken, async (req, res) => {
    try {
        const { userId1, userId2 } = req.params;
        
        const mutualFriends = await Follower.getMutualFriends(userId1, userId2);
        
        res.json({
            success: true,
            data: mutualFriends,
            total: mutualFriends.length
        });
        
    } catch (error) {
        console.error('Error getting mutual friends:', error);
        res.status(500).json({
            success: false,
            message: 'Error getting mutual friends',
            error: error.message
        });
    }
});

module.exports = router;
