const { exec } = require('child_process');
const express = require('express');
const multer = require('multer');
const { Client, LocalAuth, MessageMedia } = require('whatsapp-web.js');
const qrcode = require('qrcode');
const fs = require('fs');
const path = require('path');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 3001;

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Configure multer for file uploads (no file size limit)
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'temp/');
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname);
    }
});

const upload = multer({
    storage: storage,
    // Removed fileSize limit to allow large files
});

// Create temp directory if it doesn't exist
const tempDir = path.join(__dirname, 'temp');
if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir, { recursive: true });
}

// WhatsApp client setup
let qrPageOpened = false;
let client;
let isReady = false;
let qrCode = null;

const puppeteerOptions = {
    headless: false, // 👈 لازم FALSE علشان الواتس الأزرق
    args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-dev-shm-usage',
        '--disable-gpu'
    ]
};

function initializeWhatsApp() {
    console.log('🔄 Initializing WhatsApp client...');

    client = new Client({
        authStrategy: new LocalAuth(),
        puppeteer: puppeteerOptions
    });

client.on('qr', async (qr) => {
    const timestamp = new Date().toISOString();
    console.log(`📱 QR Code generated at: ${timestamp}`);

    try {
        qrCode = await qrcode.toDataURL(qr);

        // 🔥 افتح صفحة QR مرة واحدة فقط
        if (!qrPageOpened) {
            qrPageOpened = true;
            console.log('🌐 Opening QR page automatically...');
            exec(`start http://localhost:${PORT}/qr`);
        }

    } catch (error) {
        console.error('❌ Error generating QR code:', error);
    }
});

    client.on('ready', () => {
    console.log('✅ WhatsApp client is ready!');
    isReady = true;
    qrCode = null;
    qrPageOpened = false; // 👈 مهم
});

    client.on('authenticated', () => {
        console.log('✅ WhatsApp client is authenticated!');
    });

    client.on('auth_failure', (msg) => {
        console.error('❌ Authentication failed:', msg);
        isReady = false;
        scheduleReconnect('auth_failure');
    });

    client.on('message_create', async (msg) => {
        try {
            const fromMe = msg.fromMe ? 'Sent 📤' : 'Received 📥';
            const senderNumber = msg.from.split('@')[0];
            const pushName = msg._data?.notifyName || '';

            console.log(`${fromMe} | ${pushName ? pushName + ' ' : ''}(${senderNumber}): ${msg.body}`);

            if (msg.hasMedia) {
                console.log(`📎 Media attached: ${msg.type}`);
            }
        } catch (error) {
            console.error('Logging Error:', error.message);
        }
    });

    client.on('disconnected', (reason) => {
        console.log('⚠️ WhatsApp client disconnected:', reason);
        isReady = false;
        scheduleReconnect('disconnected');
    });

    // Initialize the client
    client.initialize().catch(error => {
        console.error('❌ Failed to initialize WhatsApp client:', error);
        scheduleReconnect('initialization_failed');
    });
}

// Auto-reconnect functionality
let reconnectTimeout;
function scheduleReconnect(reason) {
    if (reconnectTimeout) {
        clearTimeout(reconnectTimeout);
    }

    console.log(`🔄 Scheduling WhatsApp client reinitialization...`);
    console.log(`Reason: ${reason}`);

    reconnectTimeout = setTimeout(() => {
        console.log('🔄 Reinitializing WhatsApp client now...');
        try {
            if (client) {
                client.destroy().catch(() => { });
            }
        } catch (error) {
            console.error('Error destroying client:', error);
        }

        setTimeout(() => {
            initializeWhatsApp();
        }, 2000);
    }, 5000);
}

// Routes
app.get('/health', (req, res) => {
    res.json({
        status: 'healthy',
        whatsapp_ready: isReady,
        timestamp: new Date().toISOString()
    });
});

app.get('/status', (req, res) => {
    res.json({
        ready: isReady,
        qr_code: qrCode,
        timestamp: new Date().toISOString()
    });
});

app.get('/qr', (req, res) => {

    // لو واتساب جاهز → اقفل الصفحة
    if (isReady) {
        return res.send(`
            <html>
            <head>
                <title>WhatsApp Connected</title>
            </head>
            <body style="text-align:center;font-family:Arial">
                <h2>✅ WhatsApp Connected</h2>
                <p>You can close this page</p>
            </body>
            </html>
        `);
    }

    // لو لسه مفيش QR
    if (!qrCode) {
        return res.send(`
            <html>
            <head>
                <title>Waiting for QR</title>
                <meta http-equiv="refresh" content="2">
            </head>
            <body style="text-align:center;font-family:Arial">
                <h2>⏳ Waiting for QR Code...</h2>
            </body>
            </html>
        `);
    }

    // عرض QR + تحديث تلقائي
    res.send(`
        <html>
        <head>
            <title>Scan WhatsApp QR</title>
            <meta http-equiv="refresh" content="5">
        </head>
        <body style="text-align:center;font-family:Arial">
            <h2>📱 Scan QR Code</h2>
            <img src="${qrCode}" style="max-width:300px"/>
            <p>Page auto refreshes</p>
        </body>
        </html>
    `);
});

app.post('/send', async (req, res) => {
    if (!isReady) {
        return res.status(400).json({
            success: false,
            error: 'WhatsApp client is not ready'
        });
    }

    const { number, message } = req.body;

    if (!number || !message) {
        return res.status(400).json({
            success: false,
            error: 'Number and message are required'
        });
    }

    try {
        // تنظيف رقم الهاتف وتنسيقه
        let cleanNumber = number.toString().replace(/[^0-9]/g, '');

        // إضافة رمز مصر إذا لم يكن موجود
        if (!cleanNumber.startsWith('20')) {
            // إزالة 0 في البداية إذا وجدت
            if (cleanNumber.startsWith('0')) {
                cleanNumber = cleanNumber.substring(1);
            }
            cleanNumber = '20' + cleanNumber;
        }

        const chatId = `${cleanNumber}@c.us`;

        console.log(`📱 محاولة إرسال رسالة إلى: ${chatId}`);

        // التحقق من أن الرقم موجود على واتساب مع معالجة الأخطاء
        try {
            const isRegistered = await client.isRegisteredUser(chatId);
            if (!isRegistered) {
                console.error(`❌ الرقم ${cleanNumber} غير مسجل على واتساب`);
                return res.status(400).json({
                    success: false,
                    error: 'Phone number is not registered on WhatsApp'
                });
            }
        } catch (checkError) {
            // إذا فشل التحقق، نحاول الإرسال مباشرة
            console.warn(`⚠️ تعذر التحقق من الرقم، سيتم المحاولة مباشرة: ${checkError.message}`);
        }

        await client.sendMessage(chatId, message);

        console.log(`✅ تم إرسال الرسالة بنجاح إلى: ${cleanNumber}`);

        res.json({
            success: true,
            message: 'Message sent successfully',
            number: cleanNumber
        });
    } catch (error) {
        console.error('❌ Error sending message:', error);

        // إذا كان الخطأ متعلق بإغلاق الجلسة، نحاول إعادة التهيئة
        if (error.message.includes('Session closed') || error.message.includes('Protocol error')) {
            console.log('🔄 محاولة إعادة تهيئة الجلسة...');
            isReady = false;
            // لا نعيد التهيئة تلقائياً لتجنب التعارضات
        }

        res.status(500).json({
            success: false,
            error: error.message || 'Failed to send message'
        });
    }
});

app.post('/send-bulk', async (req, res) => {
    if (!isReady) {
        return res.status(400).json({
            success: false,
            error: 'WhatsApp client is not ready'
        });
    }

    const { numbers, message } = req.body;

    if (!numbers || !Array.isArray(numbers) || !message) {
        return res.status(400).json({
            success: false,
            error: 'Numbers array and message are required'
        });
    }

    const results = [];

    for (const number of numbers) {
        try {
            // تنظيف رقم الهاتف وتنسيقه
            let cleanNumber = number.toString().replace(/[^0-9]/g, '');

            // إضافة رمز مصر إذا لم يكن موجود
            if (!cleanNumber.startsWith('20')) {
                if (cleanNumber.startsWith('0')) {
                    cleanNumber = cleanNumber.substring(1);
                }
                cleanNumber = '20' + cleanNumber;
            }

            const chatId = `${cleanNumber}@c.us`;

            console.log(`📱 محاولة إرسال رسالة إلى: ${chatId}`);

            // التحقق من أن الرقم موجود على واتساب مع معالجة الأخطاء
            try {
                const isRegistered = await client.isRegisteredUser(chatId);
                if (!isRegistered) {
                    console.error(`❌ الرقم ${cleanNumber} غير مسجل على واتساب`);
                    results.push({
                        number: cleanNumber,
                        success: false,
                        error: 'Not registered on WhatsApp'
                    });
                    continue;
                }
            } catch (checkError) {
                // إذا فشل التحقق، نحاول الإرسال مباشرة
                console.warn(`⚠️ تعذر التحقق من الرقم، سيتم المحاولة مباشرة: ${checkError.message}`);
            }

            await client.sendMessage(chatId, message);
            console.log(`✅ تم إرسال الرسالة بنجاح إلى: ${cleanNumber}`);
            results.push({ number: cleanNumber, success: true });
        } catch (error) {
            console.error(`❌ Error sending to ${number}:`, error);
            results.push({ number, success: false, error: error.message });

            // إذا كان الخطأ متعلق بإغلاق الجلسة، نوقف الحلقة
            if (error.message.includes('Session closed') || error.message.includes('Protocol error')) {
                console.log('🔄 تم اكتشاف إغلاق الجلسة، إيقاف الإرسال الجماعي');
                isReady = false;
                break;
            }
        }
    }

    res.json({
        success: true,
        results: results
    });
});

app.post('/send-file', upload.single('file'), async (req, res) => {
    if (!isReady) {
        return res.status(400).json({
            success: false,
            error: 'WhatsApp client is not ready'
        });
    }

    const { number, caption } = req.body;
    const file = req.file;

    if (!number || !file) {
        return res.status(400).json({
            success: false,
            error: 'Number and file are required'
        });
    }

    try {
        const chatId = number.includes('@c.us') ? number : `${number}@c.us`;
        const filePath = file.path;
        const fileSize = fs.statSync(filePath).size;

        // For large files (>100MB), save to temp and send download link
        if (fileSize > 100 * 1024 * 1024) {
            const filename = path.basename(filePath);
            const downloadUrl = `http://localhost:${PORT}/download/${filename}`;

            const message = caption ?
                `${caption}\n\n📁 ملف كبير - اضغط للتحميل:\n${downloadUrl}` :
                `📁 ملف كبير - اضغط للتحميل:\n${downloadUrl}`;

            await client.sendMessage(chatId, message);

            res.json({
                success: true,
                message: 'Large file download link sent successfully',
                download_url: downloadUrl
            });
        } else {
            // For smaller files, send directly
            const media = MessageMedia.fromFilePath(filePath);
            await client.sendMessage(chatId, media, { caption: caption || '' });

            // Clean up the uploaded file
            fs.unlinkSync(filePath);

            res.json({
                success: true,
                message: 'File sent successfully'
            });
        }
    } catch (error) {
        console.error('❌ Error sending file:', error);

        // Clean up file on error
        if (file && file.path && fs.existsSync(file.path)) {
            fs.unlinkSync(file.path);
        }

        // Handle specific errors
        if (error.message.includes('Target closed') || error.message.includes('Protocol error')) {
            console.log('⚠️ Detected browser/session crash during send. Scheduling reconnect...');
            scheduleReconnect('protocol_error_during_send_file');
        }

        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

// Route to serve temporary files
app.get('/download/:filename', (req, res) => {
    const filename = req.params.filename;
    const filePath = path.join(tempDir, filename);

    if (!fs.existsSync(filePath)) {
        return res.status(404).json({
            success: false,
            error: 'File not found'
        });
    }

    // Set appropriate headers
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
    res.setHeader('Content-Type', 'application/octet-stream');

    // Stream the file
    const fileStream = fs.createReadStream(filePath);
    fileStream.pipe(res);

    // Clean up file after download (with delay)
    setTimeout(() => {
        if (fs.existsSync(filePath)) {
            fs.unlinkSync(filePath);
        }
    }, 1000);

    // Also clean up after 24 hours
    setTimeout(() => {
        if (fs.existsSync(filePath)) {
            fs.unlinkSync(filePath);
        }
    }, 24 * 60 * 60 * 1000);
});

app.post('/disconnect', async (req, res) => {
    try {
        if (client && isReady) {
            console.log('📱 Disconnecting WhatsApp client...');
            await client.destroy();
            isReady = false;
            qrCode = null;

            // Reinitialize to generate new QR code
            console.log('🔄 Reinitializing client to generate new QR code...');
            setTimeout(() => {
                initializeWhatsApp();
            }, 2000);

            res.json({
                success: true,
                message: 'WhatsApp client disconnected and reinitialized for new QR'
            });
        } else {
            res.json({
                success: false,
                message: 'WhatsApp client is not connected'
            });
        }
    } catch (error) {
        console.error('❌ Error disconnecting:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

app.post('/reconnect', async (req, res) => {
    try {
        if (client) {
            await client.destroy();
        }
        isReady = false;
        qrCode = null;

        setTimeout(() => {
            initializeWhatsApp();
        }, 2000);

        res.json({
            success: true,
            message: 'Reconnection initiated'
        });
    } catch (error) {
        console.error('❌ Error reconnecting:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

app.get('/chats', async (req, res) => {
    if (!isReady) {
        return res.status(400).json({
            success: false,
            error: 'WhatsApp client is not ready'
        });
    }

    try {
        const limit = parseInt(req.query.limit) || 50;
        const chats = await client.getChats();
        const chatList = chats.slice(0, limit).map(chat => ({
            id: chat.id._serialized,
            name: chat.name,
            isGroup: chat.isGroup,
            unreadCount: chat.unreadCount,
            lastMessage: chat.lastMessage ? {
                body: chat.lastMessage.body,
                timestamp: chat.lastMessage.timestamp
            } : null
        }));

        res.json({
            success: true,
            chats: chatList,
            total: chats.length,
            limit: limit,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        console.error('Error fetching chats:', error);
        res.status(500).json({
            success: false,
            error: 'Failed to fetch chats',
            message: error.message
        });
    }
});

// Initialize WhatsApp client
initializeWhatsApp();

// Error handling middleware
app.use((error, req, res, next) => {
    console.error('Server error:', error);
    res.status(500).json({
        success: false,
        error: 'Internal server error',
        message: error.message,
        timestamp: new Date().toISOString()
    });
});

// 404 handler
app.use((req, res) => {
    res.status(404).json({
        success: false,
        error: 'Endpoint not found',
        available_endpoints: [
            'GET /health',
            'GET /status',
            'GET /qr',
            'POST /send',
            'POST /send-bulk',
            'POST /send-file',
            'POST /disconnect',
            'POST /reconnect',
            'GET /chats'
        ]
    });
});

// Start server
app.listen(PORT, () => {
    console.log(`WhatsApp API server running on port ${PORT}`);
    console.log(`Health check: http://localhost:${PORT}/health`);
    console.log(`Status: http://localhost:${PORT}/status`);
    console.log(`QR Code: http://localhost:${PORT}/qr`);
    console.log(`Chats: http://localhost:${PORT}/chats`);
    console.log(`Server started at: ${new Date().toISOString()}`);
});

// Graceful shutdown
process.on('SIGINT', async () => {
    console.log('\n🔄 Shutting down gracefully...');
    try {
        if (client && isReady) {
            console.log('📱 Disconnecting WhatsApp client...');
            await client.destroy();
        }
        console.log('✅ Server shutdown complete');
        process.exit(0);
    } catch (error) {
        console.error('❌ Error during shutdown:', error);
        process.exit(1);
    }
});

// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
    console.error('❌ Uncaught Exception:', error);
    process.exit(1);
});

// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
    console.error('❌ Unhandled Rejection at:', promise, 'reason:', reason);
    process.exit(1);
});
