const { default: makeWASocket, useMultiFileAuthState, DisconnectReason } = require('@whiskeysockets/baileys');
const express = require('express');
const bodyParser = require('body-parser');
const pino = require('pino');
const fs = require('fs');

const app = express();
app.use(bodyParser.json());

const PORT = 3000;
// We use 127.0.0.1 to be safe with localhost resolution
const DJANGO_WEBHOOK = 'http://127.0.0.1:8000/webhook/whatsapp/';
const AUTH_DIR = 'baileys_auth_info';

let sock;

async function connectToWhatsApp() {
    const { state, saveCreds } = await useMultiFileAuthState(AUTH_DIR);
    
    sock = makeWASocket({
        logger: pino({ level: 'silent' }),
        printQRInTerminal: false,
        auth: state,
        browser: ["Gemini AI Bot", "Chrome", "3.0.0"],
        markOnlineOnConnect: true
    });

    sock.ev.on('creds.update', saveCreds);
    
    sock.ev.on('connection.update', (update) => {
        const { connection, lastDisconnect } = update;
        if(connection === 'close') {
            const shouldReconnect = (lastDisconnect?.error)?.output?.statusCode !== DisconnectReason.loggedOut;
            console.log('Connection closed. Reconnecting:', shouldReconnect);
            if(shouldReconnect) {
                connectToWhatsApp();
            } else {
                console.log('Logged out. Clearing session and restarting...');
                try {
                    fs.rmSync(AUTH_DIR, { recursive: true, force: true });
                    setTimeout(connectToWhatsApp, 2000); // Wait 2s before retry
                } catch (err) {
                    console.error('Failed to reset session:', err);
                }
            }
        } else if(connection === 'open') {
            console.log('WhatsApp Connection Opened!');
        }
    });

    sock.ev.on('messages.upsert', async m => {
        if(m.type === 'notify' || m.type === 'append') {
             for(const msg of m.messages) {
                 if(!msg.message) continue;
                 const key = msg.key;
                 // Ignore messages from myself
                 if (key.fromMe) continue;

                 const sender = key.remoteJid.split('@')[0]; 
                 
                 // Extract text content from various message types
                 let text = msg.message.conversation 
                            || msg.message.extendedTextMessage?.text
                            || msg.message.imageMessage?.caption;

                 if(text) {
                     console.log(`Received message from ${sender}: ${text}`);
                     
                     // Construct payload matching Meta's Webhook format
                     const payload = {
                         object: 'whatsapp_business_account',
                         entry: [{
                             changes: [{
                                 value: {
                                     messages: [{
                                         from: sender,
                                         id: key.id,
                                         text: { body: text },
                                         type: 'text'
                                     }]
                                 }
                             }]
                         }]
                     };
                     
                     try {
                         // Use built-in fetch (Node 18+)
                         const response = await fetch(DJANGO_WEBHOOK, {
                             method: 'POST',
                             headers: { 'Content-Type': 'application/json' },
                             body: JSON.stringify(payload)
                         });
                         if (!response.ok) {
                            console.error(`Django webhook error: ${response.status}`);
                         }
                     } catch(err) {
                         console.error("Failed to forward to Django:", err.message);
                     }
                 }
             }
        }
    });
}

// Start the socket logic
connectToWhatsApp();

// --- API Endpoints ---

// 1. Request Pairing Code
// Input: { phoneNumber: "15550001234" }
app.post('/pair', async (req, res) => {
    let { phoneNumber } = req.body;
    if (!phoneNumber) return res.status(400).json({ error: 'Phone number required' });

    // Sanitize: remove non-numeric chars (e.g. +62, 08-12, etc)
    phoneNumber = phoneNumber.toString().replace(/[^0-9]/g, '');

    // Helper: If it starts with '08' (common Indonesian local format), replace leading '0' with '62'
    if (phoneNumber.startsWith('08')) {
        phoneNumber = '62' + phoneNumber.substring(1);
    }
    
    if (!sock) {
        return res.status(503).json({ error: 'Socket not ready' });
    }

    try {
        // Wait a moment to ensure socket is ready for queries if we just restarted
        if (sock.authState.creds.registered) {
            return res.status(400).json({ error: "Already connected! Please delete session files to reset." });
        }
        
        console.log(`Requesting pairing code for ${phoneNumber}...`);
        const code = await sock.requestPairingCode(phoneNumber);
        console.log(`Code generated: ${code}`);
        res.json({ code });
    } catch (e) {
        console.error("Pairing error:", e);
        res.status(500).json({ error: e.message || "Failed to generate pairing code" });
    }
});

// 2. Send Message (used by Django)
// Input: { to: "15550001234", text: "Hello" }
app.post('/send', async (req, res) => {
    const { to, text } = req.body;
    if (!to || !text) return res.status(400).json({ error: "Missing 'to' or 'text'" });

    const jid = to.includes('@') ? to : `${to}@s.whatsapp.net`;
    
    try {
        await sock.sendMessage(jid, { text: text });
        res.json({ status: 'sent' });
    } catch (e) {
        console.error("Send error:", e);
        res.status(500).json({ error: e.message });
    }
});

app.listen(PORT, () => {
    console.log(`WhatsApp Bridge listening on port ${PORT}`);
});