/**
 * Message Moderation Module for Loopuman
 * Checks messages for prohibited content before allowing them through
 */

// Patterns to block
const BLOCKED_PATTERNS = {
  // Phone numbers (various formats)
  phone: [
    /\+?\d{10,15}/g,                    // +1234567890
    /\(\d{3}\)\s*\d{3}[-.]?\d{4}/g,     // (123) 456-7890
    /\d{3}[-.\s]\d{3}[-.\s]\d{4}/g,     // 123-456-7890
    /\b\d{4}[-.\s]\d{6,7}\b/g,          // UK format
  ],
  
  // Email addresses
  email: [
    /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/gi,
  ],
  
  // Social media handles/links
  social: [
    /(?!(?:LoopumanBot|Loopuman|loopuman)[^a-zA-Z0-9_])@[a-zA-Z0-9_]{3,}/g, // @username (Loopuman handles whitelisted)
    /(?:t\.me|telegram\.me)\/[a-zA-Z0-9_]+/gi,  // Telegram links
    /(?:wa\.me|whatsapp\.com)\/\d+/gi,  // WhatsApp links
    /(?:instagram\.com|ig\.me)\/[a-zA-Z0-9_.]+/gi,
    /(?:twitter\.com|x\.com)\/[a-zA-Z0-9_]+/gi,
    /(?:facebook\.com|fb\.com)\/[a-zA-Z0-9.]+/gi,
    /(?:linkedin\.com\/in)\/[a-zA-Z0-9-]+/gi,
    /discord\.gg\/[a-zA-Z0-9]+/gi,
  ],
  
  // Direct contact requests
  directContact: [
    /(?:contact|call|text|message|reach|whatsapp|telegram)\s*(?:me|us)\s*(?:at|on|via)?/gi,
    /(?:my|our)\s*(?:phone|number|email|whatsapp|telegram|insta)/gi,
    /(?:add|follow)\s*(?:me|us)\s*(?:on|at)/gi,
    /(?:dm|direct message)\s*(?:me|us)/gi,
  ],
  
  // Payment outside platform
  paymentBypass: [
    /(?:pay|send|transfer)\s*(?:me|us)\s*(?:directly|outside|via)/gi,
    /(?:paypal|venmo|cashapp|zelle|bank transfer)/gi,
    /(?:crypto|bitcoin|eth|usdt)\s*(?:address|wallet)/gi,
  ],
  
  // Illegal/harmful content keywords
  illegal: [
    /\b(?:hack|crack|pirate|torrent|warez)\b/gi,
    /\b(?:drugs?|cocaine|heroin|meth)\b/gi,
    /\b(?:weapon|gun|bomb|explosive)\b/gi,
    /\b(?:fake\s*(?:id|passport|document))\b/gi,
  ],
};

// Replacement hints for users
const VIOLATION_MESSAGES = {
  phone: '📵 Phone numbers are not allowed. Use in-app messaging.',
  email: '📧 Email addresses are not allowed. Use in-app messaging.',
  social: '🔗 Social media links/handles are not allowed.',
  directContact: '⚠️ Requests for direct contact are not allowed.',
  paymentBypass: '💰 Payment must go through Loopuman for your protection.',
  illegal: '🚫 This content violates our terms of service.',
};

/**
 * Check message for prohibited content
 * @param {string} text - The message to check
 * @returns {object} - { allowed: boolean, violations: string[], cleanedText: string }
 */
function moderateMessage(text) {
  if (!text || typeof text !== 'string') {
    return { allowed: true, violations: [], cleanedText: text };
  }
  
  const violations = [];
  let cleanedText = text;
  
  for (const [category, patterns] of Object.entries(BLOCKED_PATTERNS)) {
    for (const pattern of patterns) {
      if (pattern.test(text)) {
        violations.push({
          category,
          message: VIOLATION_MESSAGES[category],
        });
        // Reset lastIndex for global patterns
        pattern.lastIndex = 0;
        // Optionally redact the content
        cleanedText = cleanedText.replace(pattern, '[REDACTED]');
      }
    }
  }
  
  // Remove duplicates
  const uniqueViolations = violations.filter((v, i, arr) => 
    arr.findIndex(x => x.category === v.category) === i
  );
  
  return {
    allowed: uniqueViolations.length === 0,
    violations: uniqueViolations,
    cleanedText,
  };
}

/**
 * Get user-friendly error message for violations
 */
function getViolationMessage(violations) {
  if (!violations || violations.length === 0) return null;
  
  let msg = '⚠️ <b>Message Blocked</b>\n\n';
  msg += 'Your message contains prohibited content:\n\n';
  
  for (const v of violations) {
    msg += `${v.message}\n`;
  }
  
  msg += '\n💡 <i>All communication must stay within Loopuman to protect both parties.</i>';
  
  return msg;
}

module.exports = {
  moderateMessage,
  getViolationMessage,
  BLOCKED_PATTERNS,
  VIOLATION_MESSAGES,
};
