const { create } = require('venom-bot');
const express = require('express');
const path = require('path');

let client;
let qrCodeBase64 = null;
let isConnected = false;

const app = express();
app.use(express.static('public'));
app.use(express.json());

// 📄 Page avec QR Code
app.get('/login', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'login.html'));
});

// 📄 Page "connecté"
app.get('/connected', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'connected.html'));
});

// 🔄 QR code en base64 + état de connexion
app.get('/api/qrcode', (req, res) => {
  res.json({ qr: qrCodeBase64, connected: isConnected });
});

// ✅ API POST : envoie message avec boutons
app.post('/sendButtons', async (req, res) => {
  const { phone, title, message, buttons } = req.body;

  console.log('📥 Requête reçue :');
  console.log('Phone:', phone);
  console.log('Title:', title);
  console.log('Message:', message);
  console.log('Buttons brut:', buttons);

  if (!client) return res.status(500).json({ error: 'Client WhatsApp non initialisé' });
  if (!phone || !message || !title || !Array.isArray(buttons)) {
    return res.status(400).json({ error: 'Paramètres manquants ou invalides' });
  }

  try {
    const formattedButtons = buttons.map(btn => ({
      buttonText: { displayText: btn.text }
    }));

    console.log('✅ Boutons formatés pour Venom :', formattedButtons);

    await client.sendButtons(
      `${phone}@c.us`,
      title,              // ✅ OBLIGATOIRE en 1er
      message,            // ✅ Description
      formattedButtons    // ✅ Format conforme
    );

    res.json({ success: true });
  } catch (error) {
    console.error('❌ Erreur sendButtons:', error);
    res.status(500).json({ error: error.message || 'Erreur interne' });
  }
});




// ▶️ Démarrage + QR code init
create({
  session: 'session-web-api',
  catchQR: (base64Qrimg, asciiQR) => {
    qrCodeBase64 = base64Qrimg;
    isConnected = false;
  },
  puppeteerOptions: {
    headless: 'new',
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  }
}).then((cl) => {
  client = cl;

  client.onStateChange((state) => {
    if (state === 'CONNECTED') isConnected = true;
  });

  client.onStreamChange((state) => {
    if (state === 'CONNECTED') isConnected = true;
  });

}).catch((err) => {
  console.error('Erreur init Venom:', err);
});

app.listen(3001, () => console.log('🚀 Serveur lancé sur http://localhost:3001/login'));
