/**
 * WhatsApp Client using Baileys
 */

const { default: makeWASocket, DisconnectReason, useMultiFileAuthState, fetchLatestBaileysVersion } = require('@whiskeysockets/baileys');
const QRCode = require('qrcode');
const logger = require('./logger');
const { handleIncomingMessage } = require('./messageHandler');

async function createWhatsAppClient() {
    const sessionPath = './auth_info';
    const { state, saveCreds } = await useMultiFileAuthState(sessionPath);
    
    const { version } = await fetchLatestBaileysVersion();
    
    const sock = makeWASocket({
        version,
        auth: state,
        printQRInTerminal: true,
        logger: logger,
        browser: ['MikhMon Gateway', 'Chrome', '1.0.0'],
        defaultQueryTimeoutMs: undefined,
    });
    
    // Connection update handler
    sock.ev.on('connection.update', async (update) => {
        const { connection, lastDisconnect, qr } = update;
        
        if (qr) {
            logger.info('QR Code received, generating image...');
            try {
                const qrImage = await QRCode.toDataURL(qr);
                global.qrCode = qrImage;
                global.connectionStatus = 'qr_ready';
                logger.info('QR Code ready! Scan with WhatsApp app');
            } catch (err) {
                logger.error('Failed to generate QR code:', err);
            }
        }
        
        if (connection === 'close') {
            const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
            logger.warn('Connection closed. Reconnect:', shouldReconnect);
            
            global.isConnected = false;
            global.connectionStatus = 'disconnected';
            global.phoneNumber = null;
            global.qrCode = null;
            
            if (shouldReconnect) {
                logger.info('Reconnecting...');
                setTimeout(() => createWhatsAppClient(), 5000);
            } else {
                logger.info('Logged out. Please restart and scan QR code again.');
                global.connectionStatus = 'logged_out';
            }
        } else if (connection === 'open') {
            logger.info('WhatsApp connection opened successfully!');
            global.isConnected = true;
            global.connectionStatus = 'connected';
            global.qrCode = null;
            
            // Get phone number
            try {
                const user = sock.user;
                if (user && user.id) {
                    global.phoneNumber = user.id.split(':')[0];
                    logger.info(`Connected as: ${global.phoneNumber}`);
                }
            } catch (err) {
                logger.error('Failed to get phone number:', err);
            }
        } else if (connection === 'connecting') {
            logger.info('Connecting to WhatsApp...');
            global.connectionStatus = 'connecting';
        }
    });
    
    // Credentials update handler
    sock.ev.on('creds.update', saveCreds);
    
    // Message handler
    sock.ev.on('messages.upsert', async ({ messages, type }) => {
        if (type === 'notify') {
            for (const message of messages) {
                if (!message.key.fromMe) {
                    await handleIncomingMessage(sock, message);
                }
            }
        }
    });
    
    return sock;
}

/**
 * Send WhatsApp message
 */
async function sendMessage(phone, message) {
    try {
        if (!global.whatsappClient || !global.isConnected) {
            throw new Error('WhatsApp not connected');
        }
        
        // Format phone number
        let formattedPhone = phone.replace(/[^0-9]/g, '');
        
        // Add country code if not present
        if (!formattedPhone.startsWith('62')) {
            if (formattedPhone.startsWith('0')) {
                formattedPhone = '62' + formattedPhone.substring(1);
            } else {
                formattedPhone = '62' + formattedPhone;
            }
        }
        
        const jid = formattedPhone + '@s.whatsapp.net';
        
        // Send message
        await global.whatsappClient.sendMessage(jid, { text: message });
        
        logger.info(`Message sent to ${formattedPhone}`);
        
        // Log to database
        if (global.db) {
            try {
                await global.db.execute(
                    'INSERT INTO wa_message_logs (phone, message, status, sent_at) VALUES (?, ?, ?, NOW())',
                    [formattedPhone, message, 'sent']
                );
            } catch (dbErr) {
                logger.error('Failed to log message to database:', dbErr);
            }
        }
        
        return {
            success: true,
            phone: formattedPhone,
            message: 'Message sent successfully'
        };
    } catch (error) {
        logger.error('Failed to send message:', error);
        
        // Log failed message to database
        if (global.db) {
            try {
                await global.db.execute(
                    'INSERT INTO wa_message_logs (phone, message, status, error_message, sent_at) VALUES (?, ?, ?, ?, NOW())',
                    [phone, message, 'failed', error.message]
                );
            } catch (dbErr) {
                logger.error('Failed to log error to database:', dbErr);
            }
        }
        
        return {
            success: false,
            message: error.message
        };
    }
}

/**
 * Send bulk messages
 */
async function sendBulkMessages(messages) {
    const results = [];
    
    for (const msg of messages) {
        const result = await sendMessage(msg.phone, msg.message);
        results.push({
            phone: msg.phone,
            ...result
        });
        
        // Delay between messages to avoid spam detection
        await new Promise(resolve => setTimeout(resolve, 2000));
    }
    
    return results;
}

/**
 * Logout from WhatsApp
 */
async function logout() {
    try {
        if (global.whatsappClient) {
            await global.whatsappClient.logout();
            global.isConnected = false;
            global.connectionStatus = 'logged_out';
            global.phoneNumber = null;
            global.qrCode = null;
            logger.info('Logged out successfully');
            return { success: true, message: 'Logged out successfully' };
        }
        return { success: false, message: 'No active connection' };
    } catch (error) {
        logger.error('Logout error:', error);
        return { success: false, message: error.message };
    }
}

module.exports = {
    createWhatsAppClient,
    sendMessage,
    sendBulkMessages,
    logout
};
