const mongoose = require('mongoose');

const memberSchema = new mongoose.Schema({
    user_id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: [true, 'User ID is required'],
        index: true
    },
    
    name: {
        type: String,
        required: [true, 'Member name is required'],
        trim: true,
        maxlength: [100, 'Member name cannot exceed 100 characters']
    },
    
    joinDate: {
        type: Date,
        default: Date.now,
        required: true
    },
    
    // Additional member details
    role: {
        type: String,
        enum: ['member', 'admin', 'moderator'],
        default: 'member'
    },
    
    isActive: {
        type: Boolean,
        default: true
    },
    
    // Optional: Member status in the group
    status: {
        type: String,
        enum: ['active', 'inactive', 'pending', 'banned'],
        default: 'active'
    }
}, {
    timestamps: true,
    collection: 'members'
});

// Index for efficient queries
memberSchema.index({ user_id: 1 });
memberSchema.index({ joinDate: -1 });

// Static method to create member
memberSchema.statics.createMember = async function(userId, name, role = 'member') {
    console.log(`👤 [MEMBER DEBUG] Creating member for userId: ${userId}, name: ${name}`);
    
    try {
        const member = new this({
            user_id: userId,
            name: name,
            role: role,
            joinDate: new Date()
        });
        
        await member.save();
        console.log(`✅ [MEMBER DEBUG] Member created: ${member._id}`);
        
        return member;
        
    } catch (error) {
        console.error(`❌ [MEMBER ERROR] Create member failed:`, error);
        throw error;
    }
};

// Static method to get members by user ID
memberSchema.statics.getMembersByUserId = async function(userId) {
    console.log(`👤 [MEMBER DEBUG] Getting members for userId: ${userId}`);
    
    try {
        const members = await this.find({ user_id: userId })
            .populate('user_id', 'name mobile email')
            .sort({ joinDate: -1 });
        
        console.log(`📊 [MEMBER DEBUG] Found ${members.length} members for user`);
        return members;
        
    } catch (error) {
        console.error(`❌ [MEMBER ERROR] Get members by user ID failed:`, error);
        throw error;
    }
};

// Static method to get member by ID
memberSchema.statics.getMemberById = async function(memberId) {
    console.log(`👤 [MEMBER DEBUG] Getting member by ID: ${memberId}`);
    
    try {
        const member = await this.findById(memberId)
            .populate('user_id', 'name mobile email');
        
        if (member) {
            console.log(`✅ [MEMBER DEBUG] Member found: ${member._id}`);
        } else {
            console.log(`❌ [MEMBER DEBUG] Member not found: ${memberId}`);
        }
        
        return member;
        
    } catch (error) {
        console.error(`❌ [MEMBER ERROR] Get member by ID failed:`, error);
        throw error;
    }
};

module.exports = mongoose.model('Member', memberSchema);
