const AutoDirectRuleModel = require('../models/AutoDirectRuleModel') const CommentModel = require('../models/CommentModel') const MessageModel = require('../models/MessageModel') const { emitChatEvents, enrichMessage } = require('../helpers/chatHelpers') // دایرکت اتوماتیک: وقتی کسی زیر پست یه کاربر، یکی از متن‌های تریگرِ خودش رو کامنت می‌کنه، // بدون نیاز به هیچ تاییدی هم یه دایرکت براش می‌فرسته هم زیرِ همون کامنت جواب می‌ده. // content پیامِ دایرکت رو عینِ sharedPost (engagementController.js) plain-text ذخیره می‌کنیم — // چون خودِ سرور ساخته، نه متنِ رمزنگاری‌شدهٔ کاربر، محدودیتِ E2EE (chatHelpers.js) اینجا صدق نمی‌کنه async function runAutoDirectRules ({ io, postOwnerId, commenterId, commentId, postId, commentText }) { try { if (!postOwnerId || !commenterId || !postId || !commentText) return if (String(postOwnerId) === String(commenterId)) return const rules = await AutoDirectRuleModel.find({ user_id: postOwnerId, is_active: true }).lean() if (!rules.length) return const normalized = String(commentText).toLowerCase() const matched = rules.find( (r) => r.trigger_text && normalized.includes(String(r.trigger_text).toLowerCase().trim()) ) if (!matched) return const newMessage = new MessageModel({ senderId: postOwnerId, receiverId: commenterId, content: matched.direct_message }) await newMessage.save() if (io) { const formatted = await enrichMessage(newMessage) emitChatEvents(io, formatted, postOwnerId, commenterId, { type: 'chat_message', description: String(matched.direct_message).slice(0, 40) }) } await CommentModel.create({ user: postOwnerId, creator: postOwnerId, comment_for: 'post', post: postId, parent: commentId, comment: matched.reply_caption, status: 'accepted' }) await AutoDirectRuleModel.updateOne({ _id: matched._id }, { $inc: { sent_count: 1 } }) } catch (error) { console.error('Error running auto-direct rules:', error) } } module.exports = { runAutoDirectRules }