/**
 * EvolutionMessageModule.js
 * 
 * Handles incoming messages from Evolution API webhooks
 * Routes messages to correct tables based on instance_type:
 * - whatsapp_web (Baileys) → conversations + whatsapp_messages
 * - whatsapp_business (Official API) → whatsapp_cloud_conversations + whatsapp_cloud_messages
 * 
 * @module modules/whatsapp/EvolutionMessageModule
 */

const eventBus = require('../../core/whatsapp/EventBus');
const Events = require('../../core/whatsapp/CoreEvents');
const { safeExecute } = require('../../core/whatsapp/SafeExecute');
const { logInfo } = require('../../core/whatsapp/LogContext');
const { pool } = require('../../config/database');
const { logger } = require('../../config/logger');
const EvolutionInstance = require('../../models/EvolutionInstance');
const EvolutionAPIService = require('../../services/EvolutionAPIService');

class EvolutionMessageModule {
  register() {
    console.log('🔧 EvolutionMessageModule: Registrando listener para MESSAGE_RECEIVED');
    
    eventBus.on(Events.MESSAGE_RECEIVED, (payload) => {
      console.log('\n📬 EvolutionMessageModule: Evento MESSAGE_RECEIVED recebido');
      console.log('   Channel:', payload.channel);
      console.log('   Tenant ID:', payload.tenantId);
      console.log('   Instance ID:', payload.instanceId);
      
      if (payload.channel !== 'evolution') {
        console.log('   ⏭️ Ignorando: canal não é evolution');
        return;
      }
      
      console.log('   ✅ Canal correto, processando...');
      
      const context = {
        tenant_id: payload.tenantId,
        session_id: payload.sessionId || null,
        message_id: payload.message?.key?.id || null,
        module: 'evolution_message_module',
        event: 'message_received',
        step: 'dispatch'
      };
      
      safeExecute(() => this.handle(payload), context);
    });
    
    console.log('✅ EvolutionMessageModule: Listener registrado com sucesso');
  }

  async handle(payload) {
    try {
      console.log('\n      🔄 EvolutionMessageModule.handle() iniciado');
      console.log('      📦 Payload:', JSON.stringify(payload, null, 2));
      
      logInfo('Evolution message handling started', {
        tenant_id: payload.tenantId,
        instance_id: payload.instanceId,
        module: 'evolution_message_module',
        event: 'message_received',
        step: 'handle'
      });

      const { tenantId, instanceId, message } = payload;

      if (!message || !message.key) {
        console.log('      ❌ Mensagem inválida: sem message ou key');
        logger.warn('Invalid message format', { tenantId, instanceId });
        return;
      }

      console.log('      ✅ Mensagem válida');
      console.log('      🔍 Buscando instância ID:', instanceId);

      // Get instance to check type
      const instance = await EvolutionInstance.getById(instanceId);
      
      if (!instance) {
        console.log('      ❌ Instância não encontrada:', instanceId);
        logger.warn('Instance not found', { instanceId });
        return;
      }

      console.log('      ✅ Instância encontrada:', instance.instance_name);
      console.log('      📌 Tipo da instância:', instance.instance_type);
      console.log('      📌 Tipo da mensagem:', message.messageType);
      console.log('      📌 De:', message.key.remoteJid);

      logger.info('Processing Evolution message', {
        tenantId,
        instanceId,
        instanceType: instance.instance_type,
        messageType: message.messageType,
        from: message.key.remoteJid
      });

      // Route based on instance type
      if (instance.instance_type === 'whatsapp_business') {
        console.log('      🔀 Roteando para handleCloudMessage');
        // Cloud API → whatsapp_cloud_conversations + whatsapp_cloud_messages
        await this.handleCloudMessage(instance, message);
      } else {
        console.log('      🔀 Roteando para handleBaileysMessage');
        // Baileys → conversations + whatsapp_messages
        await this.handleBaileysMessage(instance, message);
      }
      
      console.log('      ✅ EvolutionMessageModule.handle() concluído\n');

    } catch (error) {
      console.error('      ❌ ERRO em EvolutionMessageModule.handle():', error.message);
      console.error('      Stack:', error.stack);
      logger.error('Error handling Evolution message', {
        error: error.message,
        stack: error.stack,
        payload
      });
    }
  }

  /**
   * Handle message for Baileys instances (conversations + whatsapp_messages)
   */
  async handleBaileysMessage(instance, message) {
    try {
      console.log('\n         💾 handleBaileysMessage iniciado');
      
      const tenantId = instance.tenant_id;
      const remoteJid = message.key.remoteJid;
      const phoneNumber = remoteJid.split('@')[0];
      const pushName = message.pushName || phoneNumber;
      const messageId = message.key.id;

      console.log('         📋 Dados da mensagem:');
      console.log('            Tenant ID:', tenantId);
      console.log('            Phone:', phoneNumber);
      console.log('            Push Name:', pushName);
      console.log('            Message ID:', messageId);

      logger.info('Handling Baileys message', {
        tenantId,
        instanceId: instance.id,
        phoneNumber,
        messageId
      });

      // Check if message already exists
      console.log('         🔍 Verificando se mensagem já existe...');
      const [existing] = await pool.query(
        'SELECT id FROM whatsapp_messages WHERE tenant_id = ? AND whatsapp_message_id = ? LIMIT 1',
        [tenantId, messageId]
      );

      if (existing.length > 0) {
        console.log('         ⏭️ Mensagem já existe, ignorando');
        logger.info('Message already exists, skipping', { messageId });
        return;
      }

      console.log('         ✅ Mensagem nova, processando...');

      // Get or create conversation
      let conversationId;
      console.log('         🔍 Buscando conversa existente...');
      const [existingConv] = await pool.query(
        'SELECT id FROM conversations WHERE tenant_id = ? AND remote_jid = ?',
        [tenantId, remoteJid]
      );

      if (existingConv.length > 0) {
        conversationId = existingConv[0].id;
        console.log('         ✅ Conversa encontrada:', conversationId);
        
        // Update conversation
        console.log('         📝 Atualizando conversa...');
        await pool.query(
          `UPDATE conversations 
           SET last_message = ?, 
               last_message_time = NOW(), 
               contact_name = ?,
               updated_at = NOW()
           WHERE id = ?`,
          [
            this.extractMessageText(message),
            pushName,
            conversationId
          ]
        );
        console.log('         ✅ Conversa atualizada');
      } else {
        console.log('         ➕ Criando nova conversa...');
        // Create new conversation (or update if exists due to race condition)
        const [result] = await pool.query(
          `INSERT INTO conversations 
           (tenant_id, instance_id, phone_number, remote_jid, contact_name, last_message, 
            last_message_time, status, stage_id, pipeline_stage, created_at, updated_at)
           VALUES (?, ?, ?, ?, ?, ?, NOW(), 'waiting', 'unassigned', 'unassigned', NOW(), NOW())
           ON DUPLICATE KEY UPDATE
             last_message = VALUES(last_message),
             last_message_time = NOW(),
             contact_name = VALUES(contact_name),
             updated_at = NOW()`,
          [
            tenantId,
            instance.id,
            phoneNumber,
            remoteJid,
            pushName,
            this.extractMessageText(message)
          ]
        );
        
        // If it was an update (not insert), get the existing conversation ID
        if (result.insertId === 0) {
          const [conv] = await pool.query(
            'SELECT id FROM conversations WHERE tenant_id = ? AND remote_jid = ?',
            [tenantId, remoteJid]
          );
          conversationId = conv[0].id;
          console.log('         ✅ Conversa atualizada (já existia):', conversationId);
        } else {
          conversationId = result.insertId;
          console.log('         ✅ Nova conversa criada:', conversationId);
        }
      }

      // Extract message content
      console.log('         📄 Extraindo conteúdo da mensagem...');
      const messageData = this.parseEvolutionMessage(message);
      console.log('         ✅ Conteúdo extraído:', messageData.type);

      // Save message
      console.log('         💾 Salvando mensagem no banco...');
      await pool.query(
        `INSERT INTO whatsapp_messages 
         (tenant_id, instance_id, connection_id, phone_number, contact_name, message_type, content, 
          media_url, media_mimetype, media_size, caption, direction, status, 
          whatsapp_message_id, conversation_id, metadata)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'incoming', 'delivered', ?, ?, ?)`,
        [
          tenantId,
          instance.id,
          null,
          phoneNumber,
          pushName,
          messageData.type,
          messageData.content,
          messageData.mediaUrl,
          messageData.mediaMimetype,
          messageData.mediaSize,
          messageData.caption,
          messageId,
          conversationId,
          JSON.stringify({
            remoteJid,
            pushName,
            evolutionInstanceId: instance.id
          })
        ]
      );

      console.log('         ✅ Mensagem salva no banco!');

      logger.info('Baileys message saved', {
        tenantId,
        conversationId,
        messageId
      });

      // Emit Socket.IO events
      console.log('         📡 Emitindo eventos Socket.IO...');
      this.emitMessageEvents(tenantId, conversationId, {
        messageId,
        phoneNumber,
        contactName: pushName,
        messageType: messageData.type,
        content: messageData.content,
        mediaUrl: messageData.mediaUrl
      });
      console.log('         ✅ Eventos Socket.IO emitidos');
      
      // Process bot logic (FAQ, Welcome Messages, AI)
      console.log('         🤖 Processando lógica de bot (FAQ, Welcome, AI)...');
      await this.processBotLogic(instance, message, phoneNumber, pushName, remoteJid, messageData);
      console.log('         ✅ Lógica de bot processada');
      
      console.log('         ✅ handleBaileysMessage concluído\n');

    } catch (error) {
      console.error('         ❌ ERRO em handleBaileysMessage:', error.message);
      console.error('         Stack:', error.stack);
      logger.error('Error handling Baileys message', {
        error: error.message,
        stack: error.stack,
        instanceId: instance.id
      });
    }
  }

  /**
   * Handle message for Cloud API instances (whatsapp_cloud_conversations + whatsapp_cloud_messages)
   */
  async handleCloudMessage(instance, message) {
    try {
      const tenantId = instance.tenant_id;
      const accountId = `evolution_${instance.id}`;
      const remoteJid = message.key.remoteJid;
      const contactPhone = remoteJid.split('@')[0];
      const contactName = message.pushName || contactPhone;
      const messageId = message.key.id;

      logger.info('Handling Cloud message', {
        tenantId,
        instanceId: instance.id,
        accountId,
        contactPhone,
        messageId
      });

      // Check if message already exists
      const [existing] = await pool.query(
        'SELECT id FROM whatsapp_cloud_messages WHERE message_id = ? LIMIT 1',
        [messageId]
      );

      if (existing.length > 0) {
        logger.info('Message already exists, skipping', { messageId });
        return;
      }

      // Get or create conversation
      let conversationId;
      const [existingConv] = await pool.query(
        'SELECT id FROM whatsapp_cloud_conversations WHERE account_id = ? AND contact_phone = ?',
        [accountId, contactPhone]
      );

      if (existingConv.length > 0) {
        conversationId = existingConv[0].id;
        
        // Update conversation
        await pool.query(
          `UPDATE whatsapp_cloud_conversations 
           SET last_message_text = ?, 
               last_message_time = NOW(), 
               last_message_from = 'customer',
               unread_count = unread_count + 1,
               contact_name = ?,
               updated_at = NOW()
           WHERE id = ?`,
          [
            this.extractMessageText(message),
            contactName,
            conversationId
          ]
        );
      } else {
        // Create new conversation
        const [result] = await pool.query(
          `INSERT INTO whatsapp_cloud_conversations 
           (tenant_id, account_id, contact_phone, contact_name, last_message_text, 
            last_message_time, last_message_from, unread_count, status, store_id, department_id)
           VALUES (?, ?, ?, ?, ?, NOW(), 'customer', 1, 'open', NULL, NULL)`,
          [
            tenantId,
            accountId,
            contactPhone,
            contactName,
            this.extractMessageText(message)
          ]
        );
        conversationId = result.insertId;
      }

      // Extract message content
      const messageData = this.parseEvolutionMessage(message);

      // Save message
      await pool.query(
        `INSERT INTO whatsapp_cloud_messages 
         (conversation_id, message_id, message_type, text_content, media_url, status)
         VALUES (?, ?, ?, ?, ?, 'delivered')`,
        [
          conversationId,
          messageId,
          messageData.type,
          messageData.content || messageData.caption || `[${messageData.type}]`,
          messageData.mediaUrl
        ]
      );

      logger.info('Cloud message saved', {
        tenantId,
        conversationId,
        messageId,
        accountId
      });

      // Emit Socket.IO events
      this.emitMessageEvents(tenantId, conversationId, {
        messageId,
        phoneNumber: contactPhone,
        contactName,
        messageType: messageData.type,
        content: messageData.content,
        mediaUrl: messageData.mediaUrl
      });

    } catch (error) {
      console.error('❌ Error handling Cloud message:', error);
      logger.error('Error handling Cloud message', {
        error: error.message,
        stack: error.stack,
        instanceId: instance.id
      });
    }
  }

  /**
   * Parse Evolution API message format
   */
  parseEvolutionMessage(message) {
    const messageType = message.messageType || 'text';
    let content = null;
    let mediaUrl = null;
    let mediaMimetype = null;
    let mediaSize = null;
    let caption = null;

    try {
      switch (messageType) {
        case 'conversation':
        case 'extendedTextMessage':
          content = message.message?.conversation || 
                   message.message?.extendedTextMessage?.text || 
                   null;
          break;

        case 'imageMessage':
          mediaUrl = message.message?.imageMessage?.url;
          mediaMimetype = message.message?.imageMessage?.mimetype;
          mediaSize = message.message?.imageMessage?.fileLength;
          caption = message.message?.imageMessage?.caption;
          content = caption || '[Image]';
          break;

        case 'videoMessage':
          mediaUrl = message.message?.videoMessage?.url;
          mediaMimetype = message.message?.videoMessage?.mimetype;
          mediaSize = message.message?.videoMessage?.fileLength;
          caption = message.message?.videoMessage?.caption;
          content = caption || '[Video]';
          break;

        case 'audioMessage':
          mediaUrl = message.message?.audioMessage?.url;
          mediaMimetype = message.message?.audioMessage?.mimetype;
          mediaSize = message.message?.audioMessage?.fileLength;
          content = '[Audio]';
          break;

        case 'documentMessage':
          mediaUrl = message.message?.documentMessage?.url;
          mediaMimetype = message.message?.documentMessage?.mimetype;
          mediaSize = message.message?.documentMessage?.fileLength;
          caption = message.message?.documentMessage?.caption;
          content = caption || message.message?.documentMessage?.fileName || '[Document]';
          break;

        case 'stickerMessage':
          mediaUrl = message.message?.stickerMessage?.url;
          mediaMimetype = message.message?.stickerMessage?.mimetype;
          content = '[Sticker]';
          break;

        case 'locationMessage':
          const loc = message.message?.locationMessage;
          content = `Location: ${loc?.degreesLatitude}, ${loc?.degreesLongitude}`;
          break;

        default:
          content = `[${messageType}]`;
      }
    } catch (error) {
      logger.error('Error parsing message', { error: error.message, messageType });
      content = '[Message]';
    }

    return {
      type: messageType,
      content,
      mediaUrl,
      mediaMimetype,
      mediaSize,
      caption
    };
  }

  /**
   * Extract simple text from message for conversation preview
   */
  extractMessageText(message) {
    const messageType = message.messageType || 'text';
    
    if (messageType === 'conversation' || messageType === 'extendedTextMessage') {
      return message.message?.conversation || 
             message.message?.extendedTextMessage?.text || 
             '[Message]';
    }
    
    return `[${messageType}]`;
  }

  /**
   * Emit Socket.IO events to tenant namespace
   */
  emitMessageEvents(tenantId, conversationId, data) {
    try {
      const io = global.io;
      if (!io) {
        logger.warn('Socket.IO not available');
        return;
      }

      const tenantNamespace = io.of(`/tenant/${tenantId}`);
      
      tenantNamespace.emit('new-message', {
        tenantId,
        messageId: data.messageId,
        conversationId,
        phoneNumber: data.phoneNumber,
        contactName: data.contactName,
        messageType: data.messageType,
        content: data.content,
        mediaUrl: data.mediaUrl,
        timestamp: new Date(),
        direction: 'incoming'
      });

      tenantNamespace.emit('new-message-alert', {
        conversationId,
        contactName: data.contactName,
        message: data.content,
        timestamp: new Date()
      });

      logger.info('Socket events emitted', { tenantId, conversationId });
    } catch (error) {
      logger.error('Error emitting socket events', { error: error.message });
    }
  }

  /**
   * Process bot logic (FAQ, Welcome Messages, AI)
   * @param {Object} instance - Evolution instance
   * @param {Object} message - WhatsApp message
   * @param {string} phoneNumber - Contact phone number
   * @param {string} pushName - Contact name
   * @param {string} remoteJid - Remote JID
   * @param {Object} messageData - Parsed message data
   */
  async processBotLogic(instance, message, phoneNumber, pushName, remoteJid, messageData) {
    try {
      const tenantId = instance.tenant_id;
      const instanceId = instance.id;

      console.log('         🤖 [Bot Logic] Iniciando processamento...');
      console.log('            Tenant ID:', tenantId);
      console.log('            Instance ID:', instanceId);
      console.log('            Phone:', phoneNumber);
      console.log('            Message Type:', messageData.type);
      console.log('            Has Text:', !!messageData.content);

      // Only process text messages
      if (messageData.type !== 'conversation' && messageData.type !== 'extendedTextMessage') {
        console.log('         ⏭️ [Bot Logic] Não é mensagem de texto, ignorando');
        return;
      }

      if (!messageData.content) {
        console.log('         ⏭️ [Bot Logic] Mensagem sem conteúdo, ignorando');
        return;
      }

      // Check bot settings
      console.log('         🔍 [Bot Logic] Verificando configurações do bot...');
      const [botSettings] = await pool.query(
        'SELECT bot_enabled, group_enabled FROM tenants WHERE id = ?',
        [tenantId]
      );

      if (botSettings.length === 0 || !botSettings[0].bot_enabled) {
        console.log('         ⏭️ [Bot Logic] Bot desabilitado para este tenant');
        return;
      }

      console.log('         ✅ [Bot Logic] Bot habilitado, continuando...');

      // Check if conversation is in manual mode and get conversation ID
      const [conversation] = await pool.query(
        'SELECT id, assigned_user_id, status FROM conversations WHERE tenant_id = ? AND phone_number = ?',
        [tenantId, phoneNumber]
      );

      if (conversation.length === 0) {
        console.log('         ⏭️ [Bot Logic] Conversa não encontrada');
        return;
      }

      const conv = conversation[0];
      const conversationId = conv.id;
      const isManualMode = conv.assigned_user_id !== null || conv.status === 'active' || conv.status === 'attended';
      
      if (isManualMode) {
        console.log('         ⏭️ [Bot Logic] Conversa em modo manual, ignorando bot');
        return;
      }

      console.log('         ✅ [Bot Logic] Conversa em modo automático (ID:', conversationId, ')');

      // Check if it's first message OF THIS CONVERSATION (for welcome messages)
      console.log('         🔍 [Bot Logic] Verificando se é primeira mensagem da conversa...');
      const [messageCount] = await pool.query(
        'SELECT COUNT(*) as count FROM whatsapp_messages WHERE tenant_id = ? AND conversation_id = ? AND direction = "incoming"',
        [tenantId, conversationId]
      );

      const isFirstMessage = messageCount[0].count <= 1;
      console.log('         📊 [Bot Logic] Total de mensagens na conversa:', messageCount[0].count, '- Primeira mensagem:', isFirstMessage);

      // Send welcome messages if first message
      if (isFirstMessage) {
        console.log('         👋 [Bot Logic] Primeira mensagem da conversa! Verificando welcome messages...');
        const welcomeSent = await this.sendWelcomeMessages(tenantId, instanceId, phoneNumber, pushName, remoteJid);
        
        if (welcomeSent) {
          console.log('         ✅ [Bot Logic] Welcome messages enviadas!');
          return; // Don't process FAQ if welcome was sent
        }
        console.log('         ⏭️ [Bot Logic] Nenhuma welcome message configurada');
      }

      // Process FAQ
      console.log('         🔍 [Bot Logic] Verificando FAQ...');
      const faqSent = await this.processFAQ(tenantId, instanceId, phoneNumber, pushName, remoteJid, messageData.content, message);
      
      if (faqSent) {
        console.log('         ✅ [Bot Logic] FAQ respondido!');
      } else {
        console.log('         ⏭️ [Bot Logic] Nenhum FAQ encontrado');
        
        // Try AI if no FAQ match
        console.log('         🤖 [Bot Logic] Verificando AI...');
        const aiSent = await this.processAI(tenantId, instanceId, phoneNumber, pushName, remoteJid, messageData.content, conversationId);
        
        if (aiSent) {
          console.log('         ✅ [Bot Logic] AI respondeu!');
        } else {
          console.log('         ⏭️ [Bot Logic] AI não configurada ou desabilitada');
        }
      }

    } catch (error) {
      console.error('         ❌ [Bot Logic] Erro:', error.message);
      logger.error('Error processing bot logic', {
        error: error.message,
        stack: error.stack,
        instanceId: instance.id
      });
    }
  }

  /**
   * Send welcome messages
   */
  async sendWelcomeMessages(tenantId, instanceId, phoneNumber, pushName, remoteJid) {
    try {
      console.log('            🔍 [Welcome] Buscando welcome messages...');
      
      // Check if already sent in last 2 hours
      const [sent] = await pool.query(
        'SELECT id FROM welcome_sent WHERE tenant_id = ? AND phone_number = ? AND sent_at > DATE_SUB(NOW(), INTERVAL 2 HOUR)',
        [tenantId, phoneNumber]
      );

      if (sent.length > 0) {
        console.log('            ⏭️ [Welcome] Já enviado nas últimas 2 horas');
        return false;
      }

      // Get welcome messages for this instance or global
      const [welcomeMessages] = await pool.query(
        `SELECT * FROM welcome_messages 
         WHERE tenant_id = ? 
         AND active = TRUE 
         AND (instance_id = ? OR instance_id IS NULL)
         ORDER BY instance_id DESC, order_position ASC`,
        [tenantId, instanceId]
      );

      console.log('            📋 [Welcome] Encontradas', welcomeMessages.length, 'mensagens');

      if (welcomeMessages.length === 0) {
        return false;
      }

      // Get instance
      const instance = await EvolutionInstance.getById(instanceId);
      if (!instance) {
        console.log('            ❌ [Welcome] Instância não encontrada');
        return false;
      }

      for (let i = 0; i < welcomeMessages.length; i++) {
        const msg = welcomeMessages[i];
        
        console.log('            📤 [Welcome] Enviando mensagem', i + 1, '/', welcomeMessages.length);
        
        // Delay before sending
        if (i === 0) {
          await new Promise(resolve => setTimeout(resolve, 7000)); // 7s before first
        } else {
          await new Promise(resolve => setTimeout(resolve, 2000)); // 2s between messages
        }

        // Replace placeholders
        let text = msg.message_text;
        text = text.replace(/\{\{customer_name\}\}/g, pushName);
        text = text.replace(/\{phone\}/g, phoneNumber);

        // Send message
        await EvolutionAPIService.sendTextMessage(
          instance.evolution_instance_id,
          remoteJid,
          text
        );
        
        console.log('            ✅ [Welcome] Mensagem', i + 1, 'enviada');
      }

      // Mark as sent
      await pool.query(
        'INSERT INTO welcome_sent (tenant_id, phone_number, sent_at) VALUES (?, ?, NOW()) ON DUPLICATE KEY UPDATE sent_at = NOW()',
        [tenantId, phoneNumber]
      );

      console.log('            ✅ [Welcome] Todas as mensagens enviadas!');
      return true;

    } catch (error) {
      console.error('            ❌ [Welcome] Erro:', error.message);
      logger.error('Error sending welcome messages', {
        error: error.message,
        tenantId,
        instanceId
      });
      return false;
    }
  }

  /**
   * Process FAQ
   */
  async processFAQ(tenantId, instanceId, phoneNumber, pushName, remoteJid, text, message) {
    try {
      console.log('            🔍 [FAQ] Buscando FAQ para:', text);
      
      const normalizedText = text.toLowerCase().trim();
      const words = normalizedText.split(/\s+/);

      // Try multiple matching strategies
      let faqs = [];
      
      // Strategy 1: Exact match
      [faqs] = await pool.query(
        `SELECT * FROM faqs 
         WHERE tenant_id = ? 
         AND active = TRUE 
         AND (instance_id = ? OR instance_id IS NULL)
         AND LOWER(question) = LOWER(?) 
         ORDER BY instance_id DESC, order_position ASC 
         LIMIT 1`,
        [tenantId, instanceId, normalizedText]
      );
      
      if (faqs.length === 0) {
        // Strategy 2: Question contains text
        [faqs] = await pool.query(
          `SELECT * FROM faqs 
           WHERE tenant_id = ? 
           AND active = TRUE 
           AND (instance_id = ? OR instance_id IS NULL)
           AND LOWER(question) LIKE LOWER(?) 
           ORDER BY instance_id DESC, order_position ASC 
           LIMIT 1`,
          [tenantId, instanceId, `%${normalizedText}%`]
        );
      }
      
      if (faqs.length === 0) {
        // Strategy 3: Text contains question
        [faqs] = await pool.query(
          `SELECT * FROM faqs 
           WHERE tenant_id = ? 
           AND active = TRUE 
           AND (instance_id = ? OR instance_id IS NULL)
           AND LOWER(?) LIKE CONCAT("%", LOWER(question), "%") 
           ORDER BY instance_id DESC, order_position ASC 
           LIMIT 1`,
          [tenantId, instanceId, normalizedText]
        );
      }

      console.log('            📋 [FAQ] Encontrados', faqs.length, 'FAQs');

      if (faqs.length === 0) {
        return false;
      }

      const faq = faqs[0];
      console.log('            ✅ [FAQ] FAQ encontrado:', faq.question);

      // Send reaction if configured
      if (faq.emoji && message.key) {
        console.log('            😊 [FAQ] Enviando reação:', faq.emoji);
        await new Promise(resolve => setTimeout(resolve, 3000));
        
        const instance = await EvolutionInstance.getById(instanceId);
        if (instance) {
          try {
            await EvolutionAPIService.sendReaction(
              instance.evolution_instance_id,
              message.key,
              faq.emoji
            );
            console.log('            ✅ [FAQ] Reação enviada');
          } catch (err) {
            console.error('            ❌ [FAQ] Erro ao enviar reação:', err.message);
          }
        }
      }

      // Wait before sending answer
      await new Promise(resolve => setTimeout(resolve, 2000));

      // Replace placeholders in answer
      let answer = faq.answer;
      answer = answer.replace(/\{\{customer_name\}\}/g, pushName);
      answer = answer.replace(/\{phone\}/g, phoneNumber);

      // Send answer
      console.log('            📤 [FAQ] Enviando resposta...');
      const instance = await EvolutionInstance.getById(instanceId);
      if (instance) {
        await EvolutionAPIService.sendTextMessage(
          instance.evolution_instance_id,
          remoteJid,
          answer
        );
        console.log('            ✅ [FAQ] Resposta enviada!');
        return true;
      }

      return false;

    } catch (error) {
      console.error('            ❌ [FAQ] Erro:', error.message);
      logger.error('Error processing FAQ', {
        error: error.message,
        tenantId,
        instanceId
      });
      return false;
    }
  }

  /**
   * Process AI response when no FAQ match
   */
  async processAI(tenantId, instanceId, phoneNumber, pushName, remoteJid, text, conversationId) {
    const crypto = require('crypto');
    const axios = require('axios');
    
    try {
      console.log('            🤖 [AI] Verificando configuração de AI...');
      
      // Get active AI configuration for this instance or tenant
      const [configs] = await pool.query(
        `SELECT * FROM ai_configurations 
         WHERE tenant_id = ? 
         AND active = TRUE 
         AND auto_response_enabled = TRUE
         AND (evolution_instance_id = ? OR evolution_instance_id IS NULL)
         ORDER BY evolution_instance_id DESC
         LIMIT 1`,
        [tenantId, instanceId]
      );

      if (configs.length === 0) {
        console.log('            ⏭️ [AI] Nenhuma configuração ativa encontrada');
        return false;
      }

      const config = configs[0];
      console.log('            ✅ [AI] Configuração encontrada:', config.persona_name, '(' + config.provider + ')');

      // Check business hours
      if (config.business_hours_start && config.business_hours_end) {
        const now = new Date();
        const currentTime = now.toTimeString().slice(0, 5);
        const currentDay = now.toLocaleDateString('en-US', { weekday: 'long' }).toLowerCase();
        
        const businessDays = (config.business_days || '').toLowerCase().split(',').map(d => d.trim());
        
        if (businessDays.length > 0 && !businessDays.includes(currentDay)) {
          console.log('            ⏭️ [AI] Fora dos dias úteis');
          return false;
        }
        
        if (currentTime < config.business_hours_start || currentTime > config.business_hours_end) {
          console.log('            ⏭️ [AI] Fora do horário comercial');
          return false;
        }
      }

      // Decrypt API key
      const apiKey = this.decryptApiKey(config.api_key);
      if (!apiKey) {
        console.log('            ❌ [AI] Falha ao descriptografar API key');
        return false;
      }

      // Get conversation history
      const historyLimit = parseInt(config.context_messages) || 10;
      console.log('            📚 [AI] Buscando histórico (últimas', historyLimit, 'mensagens)...');
      
      const [history] = await pool.query(
        `SELECT direction, content, message_type, created_at 
         FROM whatsapp_messages 
         WHERE conversation_id = ? AND tenant_id = ? 
         ORDER BY created_at DESC 
         LIMIT ?`,
        [conversationId, tenantId, historyLimit]
      );
      
      console.log('            📚 [AI] Encontradas', history.length, 'mensagens no histórico');

      // Build messages array for AI
      const messages = [];
      
      // Add system prompt
      if (config.system_prompt) {
        messages.push({
          role: 'system',
          content: config.system_prompt
        });
      }

      // Add conversation history (reversed to chronological order)
      const reversedHistory = history.reverse();
      for (const msg of reversedHistory) {
        if (msg.message_type === 'text' || msg.message_type === 'conversation' || msg.message_type === 'extendedTextMessage') {
          if (msg.content) {
            messages.push({
              role: msg.direction === 'incoming' ? 'user' : 'assistant',
              content: msg.content
            });
          }
        }
      }
      
      // Add current message if not already in history
      const lastMessage = messages.length > 0 ? messages[messages.length - 1] : null;
      if (!lastMessage || lastMessage.content !== text) {
        messages.push({
          role: 'user',
          content: text
        });
      }

      console.log('            💬 [AI] Contexto construído com', messages.length, 'mensagens');

      // Call AI API
      const apiUrl = config.provider === 'deepseek' 
        ? 'https://api.deepseek.com/v1/chat/completions'
        : 'https://api.openai.com/v1/chat/completions';

      console.log('            🌐 [AI] Chamando API:', config.provider);

      let aiResponse;
      try {
        const response = await axios.post(
          apiUrl,
          {
            model: config.model_name,
            messages: messages,
            temperature: parseFloat(config.temperature) || 0.7,
            max_tokens: parseInt(config.max_tokens) || 1000
          },
          {
            headers: {
              'Authorization': `Bearer ${apiKey}`,
              'Content-Type': 'application/json'
            },
            timeout: 30000
          }
        );

        aiResponse = response.data.choices[0].message.content;
        console.log('            ✅ [AI] Resposta recebida (', aiResponse.length, 'caracteres)');
      } catch (apiError) {
        console.error('            ❌ [AI] Erro na API:', apiError.response?.data || apiError.message);
        return false;
      }

      // Apply response delay
      const delay = (config.response_delay || 2) * 1000;
      if (delay > 0) {
        console.log('            ⏱️  [AI] Aguardando', delay, 'ms antes de responder...');
        await new Promise(resolve => setTimeout(resolve, delay));
      }

      // Send AI response
      console.log('            📤 [AI] Enviando resposta...');
      const instance = await EvolutionInstance.getById(instanceId);
      if (instance) {
        await EvolutionAPIService.sendTextMessage(
          instance.evolution_instance_id,
          remoteJid,
          aiResponse
        );
        
        // Save AI message to database
        await pool.query(
          `INSERT INTO whatsapp_messages 
           (tenant_id, connection_id, phone_number, contact_name, message_type, content, 
            direction, status, whatsapp_message_id, conversation_id, is_bot_message, metadata)
           VALUES (?, ?, ?, ?, 'text', ?, 'outgoing', 'sent', ?, ?, TRUE, ?)`,
          [
            tenantId,
            null,
            phoneNumber,
            pushName,
            aiResponse,
            `ai_${Date.now()}`,
            conversationId,
            JSON.stringify({
              ai_generated: true,
              provider: config.provider,
              model: config.model_name,
              persona: config.persona_name
            })
          ]
        );
        
        console.log('            ✅ [AI] Resposta enviada e salva!');
        return true;
      }

      return false;

    } catch (error) {
      console.error('            ❌ [AI] Erro:', error.message);
      logger.error('Error processing AI', {
        error: error.message,
        stack: error.stack,
        tenantId,
        instanceId
      });
      return false;
    }
  }

  /**
   * Decrypt API key
   */
  decryptApiKey(encryptedText) {
    const crypto = require('crypto');
    try {
      const keyString = process.env.ENCRYPTION_KEY || 'default-key-change-in-production-32';
      const key = crypto.createHash('sha256').update(keyString).digest();

      const textParts = encryptedText.split(':');
      const iv = Buffer.from(textParts.shift(), 'hex');
      const encrypted = textParts.join(':');

      const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
      let decrypted = decipher.update(encrypted, 'hex', 'utf8');
      decrypted += decipher.final('utf8');

      return decrypted;
    } catch (error) {
      logger.error('Error decrypting API key', { error: error.message });
      return null;
    }
  }
}

module.exports = { EvolutionMessageModule };
