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

/**
 * Log an analytics event to the database.
 * @param {number} userId - The ID of the user (can be null for anonymous).
 * @param {string} eventType - The type of event (e.g., 'LOGIN', 'SIGNUP', 'PAGE_VIEW').
 * @param {object} eventData - Additional JSON data for the event.
 * @param {object} req - Express request object (optional, for IP/User-Agent).
 */
const logEvent = async (userId, eventType, eventData = {}, req = null) => {
    try {
        let ipAddress = null;
        let userAgent = null;

        if (req) {
            ipAddress = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
            userAgent = req.headers['user-agent'];
        }

        await db.query(`
            INSERT INTO analytics_events (user_id, event_type, event_data, ip_address, user_agent)
            VALUES (?, ?, ?, ?, ?)
        `, [userId, eventType, JSON.stringify(eventData), ipAddress, userAgent]);

    } catch (error) {
        // Fail silently to avoid breaking the main app flow
        console.error(`[Analytics] Failed to log event ${eventType}:`, error.message);
    }
};

module.exports = { logEvent };
