const express = require('express');
const cors = require('cors');
const QRCode = require('qrcode');

const {
    default: makeWASocket,
    useMultiFileAuthState,
    DisconnectReason
} = require('@whiskeysockets/baileys');

const app = express();

app.use(cors());
app.use(express.json());

let sock = null;
let qrCodeData = null;
let connectionStatus = 'disconnected';

async function startWhatsApp(){

    const { state, saveCreds } =
    await useMultiFileAuthState('auth');

    sock = makeWASocket({
        auth: state
    });

    sock.ev.on(
        'creds.update',
        saveCreds
    );

    sock.ev.on(
        'connection.update',
        async(update) => {

            const {
                connection,
                qr,
                lastDisconnect
            } = update;

            if(qr){

                qrCodeData =
                await QRCode.toDataURL(qr);

                console.log('QR READY');

            }

            if(connection === 'open'){

                connectionStatus = 'connected';

                console.log('WHATSAPP CONNECTED');

            }

            if(connection === 'close'){

                connectionStatus = 'disconnected';

                const shouldReconnect =
                lastDisconnect?.error?.output?.statusCode
                !== DisconnectReason.loggedOut;

                if(shouldReconnect){

                    startWhatsApp();

                }

            }

        }
    );

}

startWhatsApp();

/*
|--------------------------------------------------------------------------
| STATUS
|--------------------------------------------------------------------------
*/

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

    res.json({
        status: connectionStatus
    });

});

/*
|--------------------------------------------------------------------------
| QR
|--------------------------------------------------------------------------
*/

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

    res.json({
        qr: qrCodeData
    });

});

/*
|--------------------------------------------------------------------------
| SEND MESSAGE
|--------------------------------------------------------------------------
*/

app.post('/send', async(req, res) => {

    try{

        const {
            number,
            message
        } = req.body;

        const jid =
        number + '@s.whatsapp.net';

        await sock.sendMessage(
            jid,
            {
                text: message
            }
        );

        res.json({
            success: true
        });

    }catch(error){

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

    }

});

app.listen(3000, () => {

    console.log(
        'WHATSAPP SERVER RUNNING'
    );

});