/**
 * Group Participants Event Handler
 * Handles member join/leave events
 * AI Greeting: Auto-welcome new members using DeepSeek AI
 */
import consola from 'consola';
import db from '@adonisjs/lucid/services/db';
import { generateGreeting, generateFarewell } from '#services/deepseek_service';

// Fix: Batch-load all settings in ONE query (same pattern as message.js)
async function getAllSettings() {
    try {
        const rows = await db.from('scammer_settings');
        const map = {};
        for (const r of rows) map[r.key] = r.value;
        return map;
    } catch { return {}; }
}

function getSetting(settings, key, fallback = null) {
    return (settings[key] !== undefined && settings[key] !== null) ? settings[key] : fallback;
}

// Small delay to avoid hammering the AI API when multiple members join at once
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

export default async function ({ id, sock, event }) {
    // Baileys fires group-participants.update as an array of update objects
    if (!event || !Array.isArray(event)) return;

    // Fix: Load all settings ONCE for the entire batch of updates
    const settings = await getAllSettings();

    const aiEnabled = getSetting(settings, 'ai_enabled', '0');
    const greetingEnabled = getSetting(settings, 'ai_greeting_enabled', '0');

    // Early exit if not enabled — avoid any further processing
    if (aiEnabled !== '1' || greetingEnabled !== '1') return;

    const apiKey = getSetting(settings, 'ai_api_key', '');
    if (!apiKey) {
        consola.warn(`[AI Greeting: ${id}] API key tidak dikonfigurasi. Sila tetapkan API key dalam Settings.`);
        return;
    }

    const customPrompt = getSetting(settings, 'ai_greeting_prompt', '') || '';

    for (const update of event) {
        try {
            // Only handle "add" actions (new member joins)
            // Baileys actions: 'add' | 'remove' | 'promote' | 'demote' | 'modify'
            if (update.action !== 'add' && update.action !== 'remove') continue;

            const groupJid = update.id;
            const participants = update.participants || [];
            if (!groupJid || participants.length === 0) continue;

            // Fix: Get group name from cache (with fallback)
            let groupName = groupJid.split('@')[0]; // fallback: group id number
            try {
                const meta = await sock.getGroupCache(groupJid);
                if (meta?.subject) groupName = meta.subject;
            } catch (_) {}

            consola.info(`[AI Greeting: ${id}] ${participants.length} ahli baru dalam "${groupName}"`);

            // ── LEAVE FAREWELL ────────────────────────────────────────────────
            if (update.action === 'remove') {
                const leaveEnabled = getSetting(settings, 'greeting_leave_enabled', '0');
                if (leaveEnabled === '1' && apiKey) {
                    const leavePrompt = getSetting(settings, 'greeting_leave_prompt', '') || '';
                    for (const participantJid of participants) {
                        try {
                            const memberPhone = participantJid.replace(/@[^@]+$/, '');
                            let memberName = memberPhone;
                            try {
                                const contact = sock.store?.contacts?.[participantJid];
                                if (contact?.name || contact?.notify) memberName = contact.name || contact.notify;
                            } catch (_) {}
                            consola.info(`[AI Farewell: ${id}] Menjana ucapan selamat tinggal untuk ${memberPhone} dalam "${groupName}"`);
                            const farewell = await generateFarewell(apiKey, memberName, groupName, leavePrompt);
                            if (farewell) {
                                await sock.sendMessage(groupJid, { text: farewell });
                                consola.info(`[AI Farewell: ${id}] ✅ Ucapan selamat tinggal dihantar untuk ${memberPhone}`);
                            }
                        } catch (e) {
                            consola.warn(`[AI Farewell: ${id}] Gagal untuk ${participantJid}: ${e.message}`);
                        }
                    }
                }
                continue; // Skip join logic for remove action
            }

            // ── JOIN GREETING ─────────────────────────────────────────────────
            for (let i = 0; i < participants.length; i++) {
                const participantJid = participants[i];
                try {
                    // Fix: Extract phone number properly (remove @s.whatsapp.net or @lid suffix)
                    const memberPhone = participantJid.replace(/@[^@]+$/, '');

                    // Fix: Try to get push name from Baileys contacts cache, fallback to phone
                    let memberName = memberPhone;
                    try {
                        const contact = sock.store?.contacts?.[participantJid];
                        if (contact?.name || contact?.notify) {
                            memberName = contact.name || contact.notify;
                        }
                    } catch (_) {}

                    // Normalize JID to @s.whatsapp.net for mention
                    const mentionJid = participantJid.includes('@')
                        ? participantJid
                        : `${memberPhone}@s.whatsapp.net`;

                    consola.info(`[AI Greeting: ${id}] Menjana ucapan untuk ${memberName} (${memberPhone}) dalam "${groupName}"`);

                    const greeting = await generateGreeting(apiKey, memberName, groupName, customPrompt);

                    if (greeting) {
                        await sock.sendMessage(groupJid, {
                            text: greeting,
                            mentions: [mentionJid],
                        });
                        consola.info(`[AI Greeting: ${id}] ✅ Ucapan dihantar untuk ${memberPhone} dalam "${groupName}"`);
                    } else {
                        consola.warn(`[AI Greeting: ${id}] generateGreeting pulangkan kosong untuk ${memberPhone}`);
                    }

                    // Fix: Small delay between members to avoid rate limiting
                    if (i < participants.length - 1) await sleep(1000);

                } catch (e) {
                    consola.warn(`[AI Greeting: ${id}] Gagal untuk ${participantJid}: ${e.message}`);
                }
            }

        } catch (e) {
            consola.warn(`[AI GroupParticipants: ${id}] Error memproses update:`, e.message);
        }
    }
}
