const mongoose = require('mongoose');

const followersSchema = new mongoose.Schema({
    // The user who is following
    followerId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: [true, 'Follower ID is required'],
        index: true
    },
    
    // The user being followed
    followingId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: [true, 'Following ID is required'],
        index: true
    },
    
    // Status of the follow request
    status: {
        type: String,
        enum: ['accepted', 'rejected', 'requested'],
        default: 'requested',
        required: true,
        index: true
    },
    
    // When the follow request was made
    requestedAt: {
        type: Date,
        default: Date.now,
        required: true
    },
    
    // When the request was accepted/rejected
    respondedAt: {
        type: Date,
        default: null
    },
    
    // Optional message with the follow request
    message: {
        type: String,
        trim: true,
        maxlength: [200, 'Message cannot exceed 200 characters'],
        default: ''
    },
    
    // Whether the follow is active (not blocked/unfollowed)
    isActive: {
        type: Boolean,
        default: true,
        index: true
    },
    
    // Whether notifications are enabled for this follow
    notificationsEnabled: {
        type: Boolean,
        default: true
    }
}, {
    timestamps: true
});

// Compound indexes for efficient queries
followersSchema.index({ followerId: 1, followingId: 1 }, { unique: true });
followersSchema.index({ followerId: 1, status: 1 });
followersSchema.index({ followingId: 1, status: 1 });
followersSchema.index({ followerId: 1, isActive: 1 });
followersSchema.index({ followingId: 1, isActive: 1 });

// Static method to get followers of a user
followersSchema.statics.getFollowers = async function(userId, status = 'accepted') {
    console.log(`👥 [FOLLOWERS DEBUG] Getting followers for userId: ${userId}, status: ${status}`);
    
    try {
        const followers = await this.find({
            followingId: userId,
            status: status,
            isActive: true
        })
        .populate('followerId', 'name mobile profileImage about interests occupation schoolDetails collegeDetails state district nativePlace pincodeNative')
        .sort({ requestedAt: -1 });
        
        console.log(`✅ [FOLLOWERS DEBUG] Found ${followers.length} followers`);
        return followers;
        
    } catch (error) {
        console.error(`❌ [FOLLOWERS ERROR] Get followers failed:`, error);
        throw error;
    }
};

// Static method to get users that a user is following
followersSchema.statics.getFollowing = async function(userId, status = 'accepted') {
    console.log(`👥 [FOLLOWING DEBUG] Getting following for userId: ${userId}, status: ${status}`);
    
    try {
        const following = await this.find({
            followerId: userId,
            status: status,
            isActive: true
        })
        .populate('followingId', 'name mobile profileImage about interests occupation schoolDetails collegeDetails state district nativePlace pincodeNative')
        .sort({ requestedAt: -1 });
        
        console.log(`✅ [FOLLOWING DEBUG] Found ${following.length} following`);
        return following;
        
    } catch (error) {
        console.error(`❌ [FOLLOWING ERROR] Get following failed:`, error);
        throw error;
    }
};

// Static method to get mutual connections
followersSchema.statics.getMutualConnections = async function(userId1, userId2) {
    console.log(`🤝 [MUTUAL DEBUG] Getting mutual connections between ${userId1} and ${userId2}`);
    
    try {
        // Get users that both users are following
        const user1Following = await this.find({
            followerId: userId1,
            status: 'accepted',
            isActive: true
        }).select('followingId');
        
        const user2Following = await this.find({
            followerId: userId2,
            status: 'accepted',
            isActive: true
        }).select('followingId');
        
        const user1FollowingIds = user1Following.map(f => f.followingId.toString());
        const user2FollowingIds = user2Following.map(f => f.followingId.toString());
        
        // Find mutual connections
        const mutualIds = user1FollowingIds.filter(id => user2FollowingIds.includes(id));
        
        if (mutualIds.length === 0) {
            console.log(`✅ [MUTUAL DEBUG] No mutual connections found`);
            return [];
        }
        
        const User = require('./User');
        const mutualConnections = await User.find({
            _id: { $in: mutualIds }
        }).select('name mobile profileImage about interests occupation');
        
        console.log(`✅ [MUTUAL DEBUG] Found ${mutualConnections.length} mutual connections`);
        return mutualConnections;
        
    } catch (error) {
        console.error(`❌ [MUTUAL ERROR] Get mutual connections failed:`, error);
        throw error;
    }
};

// Static method to check if user A follows user B
followersSchema.statics.isFollowing = async function(followerId, followingId) {
    console.log(`🔍 [FOLLOW CHECK DEBUG] Checking if ${followerId} follows ${followingId}`);
    
    try {
        const follow = await this.findOne({
            followerId: followerId,
            followingId: followingId,
            isActive: true
        });
        
        const isFollowing = !!follow;
        const status = follow ? follow.status : null;
        
        console.log(`✅ [FOLLOW CHECK DEBUG] Is following: ${isFollowing}, Status: ${status}`);
        return { isFollowing, status, follow };
        
    } catch (error) {
        console.error(`❌ [FOLLOW CHECK ERROR] Check follow failed:`, error);
        throw error;
    }
};

// Static method to get follow request counts
followersSchema.statics.getFollowCounts = async function(userId) {
    console.log(`📊 [FOLLOW COUNTS DEBUG] Getting follow counts for userId: ${userId}`);
    
    try {
        const followersCount = await this.countDocuments({
            followingId: userId,
            status: 'accepted',
            isActive: true
        });
        
        const followingCount = await this.countDocuments({
            followerId: userId,
            status: 'accepted',
            isActive: true
        });
        
        const pendingRequestsCount = await this.countDocuments({
            followingId: userId,
            status: 'requested',
            isActive: true
        });
        
        const sentRequestsCount = await this.countDocuments({
            followerId: userId,
            status: 'requested',
            isActive: true
        });
        
        const counts = {
            followers: followersCount,
            following: followingCount,
            pendingRequests: pendingRequestsCount,
            sentRequests: sentRequestsCount
        };
        
        console.log(`✅ [FOLLOW COUNTS DEBUG] Counts:`, counts);
        return counts;
        
    } catch (error) {
        console.error(`❌ [FOLLOW COUNTS ERROR] Get follow counts failed:`, error);
        throw error;
    }
};

module.exports = mongoose.model('Followers', followersSchema);

