const { Client, LocalAuth } = require('whatsapp-web.js');

const number = process.argv[2];
const message = process.argv[3];

if (!number || !message) {
    console.log('Usage: node sendWhatsappText.js 201224228010 "Hello world"');
    process.exit(1);
}

const client = new Client({
    authStrategy: new LocalAuth({ clientId: 'main' }),
    puppeteer: {
        headless: false,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    }
});

client.on('qr', () => {
    console.log('Scan QR Code');
});

client.on('ready', async () => {
    try {
        console.log('WhatsApp Ready');

        const chatId = number.replace(/\D/g, '') + '@c.us';

        const isRegistered = await client.isRegisteredUser(chatId);
        if (!isRegistered) {
            throw new Error('Number is NOT registered on WhatsApp');
        }

        await client.sendMessage(chatId, message);
        console.log('✔ Text Sent Successfully');

        // نغلق Node بعد الإرسال بهدوء
        setTimeout(async () => {
            await client.destroy();
            process.exit(0);
        }, 2000);

    } catch (err) {
        console.error('Send Error:', err.message);
    }
});

client.initialize();
