// Audit Log Helper
// Fire-and-forget insert - never blocks the response
const pool = require('../db');

function logAudit({ userId, username, action, entityType, entityId, details, ipAddress }) {
    const detailsStr = details && typeof details === 'object'
        ? JSON.stringify(details)
        : details || null;

    pool.query(
        `INSERT INTO audit_logs (user_id, username, action, entity_type, entity_id, details, ip_address)
         VALUES ($1, $2, $3, $4, $5, $6, $7)`,
        [userId || null, username || 'unknown', action, entityType, entityId || null, detailsStr, ipAddress || null]
    ).catch((err) => {
        console.error('Audit log error:', err.message);
    });
}

module.exports = logAudit;
