const mongoose = require('mongoose');

const groupMessageSchema = new mongoose.Schema({
    groupId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Group',
        required: [true, 'Group ID is required'],
        index: true
    },
    
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: [true, 'User ID is required'],
        index: true
    },
    
    message: {
        type: String,
        required: [true, 'Message content is required'],
        trim: true,
        maxlength: [1000, 'Message cannot exceed 1000 characters']
    },
    
    messageType: {
        type: String,
        enum: ['text', 'image', 'video', 'file', 'system'],
        default: 'text'
    },
    
    // For media messages
    media: {
        fileName: {
            type: String,
            trim: true
        },
        filePath: {
            type: String,
            trim: true
        },
        url: {
            type: String,
            trim: true
        },
        originalName: {
            type: String,
            trim: true
        },
        size: {
            type: Number,
            min: [0, 'File size cannot be negative']
        },
        mimeType: {
            type: String,
            trim: true
        },
        thumbnail: {
            type: String,
            trim: true
        }
    },
    
    // Message status
    isEdited: {
        type: Boolean,
        default: false
    },
    
    editedAt: {
        type: Date
    },
    
    isDeleted: {
        type: Boolean,
        default: false
    },
    
    deletedAt: {
        type: Date
    },
    
    // Reactions/Engagement
    reactions: [{
        userId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User',
            required: true
        },
        emoji: {
            type: String,
            required: true,
            trim: true
        },
        reactedAt: {
            type: Date,
            default: Date.now
        }
    }],
    
    // Message visibility
    isVisible: {
        type: Boolean,
        default: true
    },
    
    // Reply to another message
    replyTo: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'GroupMessage',
        default: null
    },
    
    // Message metadata
    metadata: {
        clientMessageId: String, // For frontend message tracking
        deviceInfo: String,      // Device/browser info
        ipAddress: String        // User's IP address
    }
}, {
    timestamps: true,
    collection: 'group_messages'
});

// Indexes for efficient querying
groupMessageSchema.index({ groupId: 1, createdAt: -1 });
groupMessageSchema.index({ userId: 1, createdAt: -1 });
groupMessageSchema.index({ messageType: 1, createdAt: -1 });
groupMessageSchema.index({ isVisible: 1, createdAt: -1 });

// Static method to get recent messages for a group
groupMessageSchema.statics.getRecentMessages = async function(groupId, limit = 500, offset = 0) {
    console.log(`💬 [GROUP MESSAGE DEBUG] Getting recent messages for group: ${groupId}`);
    console.log(`💬 [GROUP MESSAGE DEBUG] Limit: ${limit}, Offset: ${offset}`);
    
    try {
        const messages = await this.find({
            groupId: groupId,
            isVisible: true,
            isDeleted: false
        })
        .populate('userId', 'name mobile profileImage')
        .populate('replyTo', 'message userId')
        .sort({ createdAt: -1 })
        .limit(limit)
        .skip(offset);
        
        console.log(`💬 [GROUP MESSAGE DEBUG] Found ${messages.length} messages`);
        
        // Reverse to get chronological order (oldest first)
        return messages.reverse();
        
    } catch (error) {
        console.error(`❌ [GROUP MESSAGE ERROR] Get recent messages failed:`, error);
        throw error;
    }
};

// Static method to get message count for a group
groupMessageSchema.statics.getMessageCount = async function(groupId) {
    console.log(`💬 [GROUP MESSAGE DEBUG] Getting message count for group: ${groupId}`);
    
    try {
        const count = await this.countDocuments({
            groupId: groupId,
            isVisible: true,
            isDeleted: false
        });
        
        console.log(`💬 [GROUP MESSAGE DEBUG] Message count: ${count}`);
        return count;
        
    } catch (error) {
        console.error(`❌ [GROUP MESSAGE ERROR] Get message count failed:`, error);
        throw error;
    }
};

// Static method to search messages
groupMessageSchema.statics.searchMessages = async function(groupId, searchTerm, limit = 100) {
    console.log(`💬 [GROUP MESSAGE DEBUG] Searching messages in group: ${groupId}`);
    console.log(`💬 [GROUP MESSAGE DEBUG] Search term: ${searchTerm}`);
    
    try {
        const messages = await this.find({
            groupId: groupId,
            message: { $regex: searchTerm, $options: 'i' },
            isVisible: true,
            isDeleted: false
        })
        .populate('userId', 'name mobile')
        .sort({ createdAt: -1 })
        .limit(limit);
        
        console.log(`💬 [GROUP MESSAGE DEBUG] Found ${messages.length} matching messages`);
        return messages;
        
    } catch (error) {
        console.error(`❌ [GROUP MESSAGE ERROR] Search messages failed:`, error);
        throw error;
    }
};

// Instance method to add reaction
groupMessageSchema.methods.addReaction = function(userId, emoji) {
    console.log(`💬 [REACTION DEBUG] Adding reaction ${emoji} from user ${userId} to message ${this._id}`);
    
    // Remove existing reaction from this user
    this.reactions = this.reactions.filter(reaction => 
        reaction.userId.toString() !== userId.toString()
    );
    
    // Add new reaction
    this.reactions.push({
        userId: userId,
        emoji: emoji,
        reactedAt: new Date()
    });
    
    return this.save();
};

// Instance method to remove reaction
groupMessageSchema.methods.removeReaction = function(userId) {
    console.log(`💬 [REACTION DEBUG] Removing reaction from user ${userId} to message ${this._id}`);
    
    this.reactions = this.reactions.filter(reaction => 
        reaction.userId.toString() !== userId.toString()
    );
    
    return this.save();
};

// Instance method to edit message
groupMessageSchema.methods.editMessage = function(newMessage) {
    console.log(`💬 [EDIT DEBUG] Editing message ${this._id}`);
    
    this.message = newMessage;
    this.isEdited = true;
    this.editedAt = new Date();
    
    return this.save();
};

// Instance method to delete message (soft delete)
groupMessageSchema.methods.deleteMessage = function() {
    console.log(`💬 [DELETE DEBUG] Soft deleting message ${this._id}`);
    
    this.isDeleted = true;
    this.deletedAt = new Date();
    this.message = '[Message deleted]';
    
    return this.save();
};

module.exports = mongoose.model('GroupMessage', groupMessageSchema);
