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 currentQR = null;
let isConnected = false;

/*
|--------------------------------------------------------------------------
| INICIAR WHATSAPP
|--------------------------------------------------------------------------
*/

async function startWhatsApp() {

    const { state, saveCreds } =
    await useMultiFileAuthState("session");

    sock = makeWASocket({
        auth: state,
        printQRInTerminal: true
    });

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

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

        const {
            connection,
            qr,
            lastDisconnect
        } = update;

        if(qr){

            currentQR =
            await QRCode.toDataURL(qr);

            console.log("QR generado");

        }

        if(connection === "open"){

            console.log("WhatsApp conectado");

            isConnected = true;

            currentQR = null;

        }

        if(connection === "close"){

            isConnected = false;

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

            console.log("WhatsApp desconectado");

            if(shouldReconnect){

                startWhatsApp();

            }

        }

    });

}

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

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

    if(currentQR){

        return res.send(`
            <html>
            <body style="font-family:Arial;text-align:center;padding-top:40px;">
                <h2>Escanea el QR</h2>
                <img src="${currentQR}" />
            </body>
            </html>
        `);

    }

    if(isConnected){

        return res.send("WhatsApp conectado");

    }

    return res.send("Generando QR...");

});

/*
|--------------------------------------------------------------------------
| ENVIAR MENSAJE
|--------------------------------------------------------------------------
*/

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

    try{

        const {
            number,
            message
        } = req.body;

        if(!number || !message){

            return res.json({
                success:false,
                error:"Faltan datos"
            });

        }

        const jid =
        number.replace(/\D/g,'') +
        "@s.whatsapp.net";

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

        return res.json({
            success:true
        });

    }catch(error){

        console.log(error);

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

    }

});

/*
|--------------------------------------------------------------------------
| SERVIDOR
|--------------------------------------------------------------------------
*/

const PORT =
process.env.PORT || 3000;

app.listen(PORT, () => {

    console.log(
        "API iniciada en puerto " + PORT
    );

});

startWhatsApp();