/**
 * API Routes
 */

const express = require('express');
const router = express.Router();
const { sendMessage, sendBulkMessages, logout } = require('./whatsapp');
const logger = require('./logger');

// Middleware to check API key
function checkApiKey(req, res, next) {
    const apiKey = req.headers['x-api-key'] || req.query.api_key;
    
    if (!apiKey || apiKey !== process.env.API_KEY) {
        return res.status(401).json({
            success: false,
            message: 'Unauthorized: Invalid API key'
        });
    }
    
    next();
}

/**
 * GET /api/status
 * Get WhatsApp connection status
 */
router.get('/status', (req, res) => {
    res.json({
        success: true,
        connected: global.isConnected,
        status: global.connectionStatus,
        phone: global.phoneNumber,
        hasQR: !!global.qrCode
    });
});

/**
 * GET /api/qr
 * Get QR code for authentication
 */
router.get('/qr', (req, res) => {
    if (global.isConnected) {
        return res.json({
            success: false,
            message: 'Already connected',
            phone: global.phoneNumber
        });
    }
    
    if (!global.qrCode) {
        return res.json({
            success: false,
            message: 'QR code not ready yet. Please wait...',
            status: global.connectionStatus
        });
    }
    
    res.json({
        success: true,
        qrCode: global.qrCode,
        message: 'Scan this QR code with WhatsApp app'
    });
});

/**
 * POST /api/send
 * Send single message
 * Body: { phone, message }
 */
router.post('/send', checkApiKey, async (req, res) => {
    try {
        const { phone, message } = req.body;
        
        if (!phone || !message) {
            return res.status(400).json({
                success: false,
                message: 'Phone and message are required'
            });
        }
        
        if (!global.isConnected) {
            return res.status(503).json({
                success: false,
                message: 'WhatsApp not connected',
                status: global.connectionStatus
            });
        }
        
        const result = await sendMessage(phone, message);
        
        res.json(result);
    } catch (error) {
        logger.error('Send message error:', error);
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
});

/**
 * POST /api/send-bulk
 * Send multiple messages
 * Body: { messages: [{ phone, message }, ...] }
 */
router.post('/send-bulk', checkApiKey, async (req, res) => {
    try {
        const { messages } = req.body;
        
        if (!messages || !Array.isArray(messages)) {
            return res.status(400).json({
                success: false,
                message: 'Messages array is required'
            });
        }
        
        if (!global.isConnected) {
            return res.status(503).json({
                success: false,
                message: 'WhatsApp not connected',
                status: global.connectionStatus
            });
        }
        
        const results = await sendBulkMessages(messages);
        
        const successCount = results.filter(r => r.success).length;
        const failedCount = results.length - successCount;
        
        res.json({
            success: true,
            total: results.length,
            sent: successCount,
            failed: failedCount,
            results: results
        });
    } catch (error) {
        logger.error('Send bulk error:', error);
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
});

/**
 * POST /api/logout
 * Logout from WhatsApp
 */
router.post('/logout', checkApiKey, async (req, res) => {
    try {
        const result = await logout();
        res.json(result);
    } catch (error) {
        logger.error('Logout error:', error);
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
});

/**
 * POST /api/restart
 * Restart WhatsApp connection
 */
router.post('/restart', checkApiKey, async (req, res) => {
    try {
        logger.info('Restarting WhatsApp connection...');
        
        if (global.whatsappClient) {
            await global.whatsappClient.logout();
        }
        
        // Reinitialize
        const { createWhatsAppClient } = require('./whatsapp');
        setTimeout(async () => {
            global.whatsappClient = await createWhatsAppClient();
        }, 2000);
        
        res.json({
            success: true,
            message: 'Restarting WhatsApp connection...'
        });
    } catch (error) {
        logger.error('Restart error:', error);
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
});

/**
 * GET /api/logs
 * Get message logs
 */
router.get('/logs', checkApiKey, async (req, res) => {
    try {
        const limit = parseInt(req.query.limit) || 50;
        const [rows] = await global.db.execute(
            'SELECT * FROM wa_message_logs ORDER BY id DESC LIMIT ?',
            [limit]
        );
        
        res.json({
            success: true,
            count: rows.length,
            logs: rows
        });
    } catch (error) {
        logger.error('Get logs error:', error);
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
});

module.exports = router;
