/**
 * 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 } from '#services/deepseek_service';

async function getSetting(key, fallback = null) {
    try {
        const row = await db.from('scammer_settings').where('key', key).first();
        return row ? row.value : fallback;
    } catch {
        return fallback;
    }
}

export default async function ({ id, sock, event }) {
    // event is an array of group participant updates
    if (!event || !Array.isArray(event)) return;

    for (const update of event) {
        try {
            // Only handle "add" actions (new member joins)
            if (update.action !== 'add') continue;

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

            // Check AI + Greeting enabled
            const aiEnabled = await getSetting('ai_enabled', '0');
            const greetingEnabled = await getSetting('ai_greeting_enabled', '0');
            if (aiEnabled !== '1' || greetingEnabled !== '1') continue;

            const apiKey = await getSetting('ai_api_key', '');
            if (!apiKey) {
                consola.warn(`[AI Greeting: ${id}] API key tidak dikonfigurasi.`);
                continue;
            }

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

            // Get group name from cache
            let groupName = groupJid;
            try {
                const meta = await sock.getGroupCache(groupJid);
                if (meta?.subject) groupName = meta.subject;
            } catch (_) {}

            for (const participantJid of participants) {
                try {
                    // Extract phone/name from JID
                    const memberPhone = participantJid.replace(/@.*$/, '');
                    const memberName = memberPhone; // Use phone as fallback name

                    consola.info(`[AI Greeting: ${id}] Generating greeting for ${memberPhone} in ${groupName}`);

                    const greeting = await generateGreeting(apiKey, memberName, groupName, customPrompt);
                    if (greeting) {
                        // Send greeting mentioning the new member
                        const mentionJid = participantJid.endsWith('@s.whatsapp.net') ? participantJid : `${memberPhone}@s.whatsapp.net`;
                        await sock.sendMessage(groupJid, {
                            text: greeting,
                            mentions: [mentionJid],
                        });
                        consola.info(`[AI Greeting: ${id}] ✅ Ucapan dihantar untuk ${memberPhone} dalam ${groupName}`);
                    }
                } catch (e) {
                    consola.warn(`[AI Greeting: ${id}] Gagal untuk ${participantJid}: ${e.message}`);
                }
            }
        } catch (e) {
            consola.warn(`[AI GroupParticipants: ${id}] Error:`, e.message);
        }
    }
}
