/**
 * Handle incoming WhatsApp messages
 */

const axios = require('axios');
const logger = require('./logger');

/**
 * Handle incoming message from WhatsApp
 */
async function handleIncomingMessage(sock, message) {
    try {
        // Extract message data
        const from = message.key.remoteJid;
        const phone = from.split('@')[0];
        const messageText = message.message?.conversation || 
                           message.message?.extendedTextMessage?.text || '';
        
        if (!messageText) {
            return; // Ignore non-text messages
        }
        
        logger.info(`Incoming message from ${phone}: ${messageText}`);
        
        // Log to database
        if (global.db) {
            try {
                await global.db.execute(
                    'INSERT INTO wa_message_logs (phone, message, direction, received_at) VALUES (?, ?, ?, NOW())',
                    [phone, messageText, 'incoming']
                );
            } catch (dbErr) {
                logger.error('Failed to log incoming message:', dbErr);
            }
        }
        
        // Forward to MikhMon webhook
        const webhookUrl = process.env.WEBHOOK_URL;
        if (webhookUrl) {
            try {
                await axios.post(webhookUrl, {
                    sender: phone,
                    message: messageText,
                    timestamp: new Date().toISOString(),
                    messageId: message.key.id
                }, {
                    timeout: 5000
                });
                logger.info(`Message forwarded to webhook: ${webhookUrl}`);
            } catch (webhookErr) {
                logger.error('Failed to forward to webhook:', webhookErr.message);
            }
        }
        
        // Auto-reply for specific commands (optional)
        await handleCommands(sock, from, messageText);
        
    } catch (error) {
        logger.error('Error handling incoming message:', error);
    }
}

/**
 * Handle bot commands
 */
async function handleCommands(sock, from, message) {
    const msg = message.toLowerCase().trim();
    
    // Ping command
    if (msg === 'ping') {
        await sock.sendMessage(from, { 
            text: '🤖 Pong! Bot is active and running.' 
        });
    }
    
    // Status command
    else if (msg === 'status') {
        const status = `📊 *Bot Status*\n\n` +
                      `✅ Connected: ${global.isConnected}\n` +
                      `📱 Phone: ${global.phoneNumber || 'N/A'}\n` +
                      `⏱️ Uptime: ${Math.floor(process.uptime())} seconds`;
        
        await sock.sendMessage(from, { text: status });
    }
}

module.exports = {
    handleIncomingMessage
};
