/**
 * Discord Action Log — persistent audit trail for Arbiter's Discord actions.
 * REQ-2026-04-15-discord-action-log (Chronicler #92, Issue #1)
 *
 * Silent-fail pattern: never let logging break the action it's logging.
 * Every function swallows errors internally and logs to console as fallback.
 *
 * Action types:
 *   reaction_role_add      — emoji reaction → role assigned
 *   reaction_role_remove   — emoji reaction removed → role removed
 *   wanderer_assigned      — new member → Wanderer role
 *   welcome_dm             — new member → welcome DM (success or DMs closed)
 *   link_reminder_dm       — post-checkout → link reminder DM
 */

const db = require('../database');

/**
 * @param {string} actionType  — one of the action type constants above
 * @param {string|null} discordId
 * @param {string|null} username
 * @param {object} details     — arbitrary JSON payload (role ID, emoji, etc.)
 * @param {boolean} success
 * @param {string|null} errorMessage
 */
async function logAction(actionType, discordId, username, details, success, errorMessage) {
    try {
        await db.query(
            `INSERT INTO discord_action_log
               (action_type, discord_id, username, details, success, error_message)
             VALUES ($1, $2, $3, $4, $5, $6)`,
            [
                actionType,
                discordId || null,
                username || null,
                JSON.stringify(details || {}),
                success !== false,
                errorMessage || null
            ]
        );
    } catch (err) {
        // Fallback: at least the console has it
        console.error('[DiscordActionLog] DB write failed:', err.message,
            { actionType, discordId, username });
    }
}

module.exports = { logAction };
