const loggerService = require('./start');

// Import the MySQL pools from your database service
const pools = require('../database/pools').get();

// Name of the database used for logging
const dbName = 'logging';

// Get the Write pool with the "system" role
const writePool = pools[dbName].w.s;

/*
    * Generic function to write log data to any table
    * @param {string} tableName - Name of the table to write to
    * @param {Object} logData - Key/value pairs representing columns and values
    * @returns {Object} - Success status and optional error
*/
async function writeToTable(tableName, logData) {
    // Check if logger is active
    if (!loggerService.online()) {
        return { success: false, error: 'Logger is inactive' };
    }

    // Validate input
    if (!tableName || !logData) throw new Error('Table name and log data are required');

    // Extract columns and values dynamically from the logData object
    const columns = Object.keys(logData).join(', '); // e.g., "user, action, success"
    const placeholders = Object.keys(logData).map(() => '?').join(', '); // e.g., "?, ?, ?"
    const values = Object.values(logData); // e.g., ["user", "login", true]

    // Build the INSERT SQL statement
    const sql = `INSERT INTO ${tableName} (${columns}) VALUES (${placeholders})`;

    try {
        // Execute the query on the write pool
        await writePool.query(sql, values);

        // Return success
        return { success: true };
    } catch (err) {
        // Log the error to the console for debugging
        console.error('Error writing log to DB:', err);

        // Return failure state
        return { success: false, error: err };
    }
}

/*
    * Generic write function for any other log types.
    * This allows dynamic handling of new log types without modifying the module.
*/
module.exports.write = async function(logData, tableName) {
    return writeToTable(tableName, logData);
};