const { getDb } = require('../database');

function logAction(userId, userEmail, userName, action, details, req) {
  try {
    const db = getDb();
    const ip = req ? (req.headers['x-forwarded-for'] || req.socket?.remoteAddress || '') : '';
    const ua = req ? (req.headers['user-agent'] || '') : '';
    db.prepare(`
      INSERT INTO audit_logs (user_id, user_email, user_name, action, details, ip_address, user_agent)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `).run(userId, userEmail, userName, action, details, ip, ua);
  } catch (err) {
    console.error('Audit log error:', err.message);
  }
}

module.exports = { logAction };
