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

const logActivity = (action, module, recordId = null, details = '') => {
  return (req, res, next) => {
    const originalSend = res.send;
    
    res.send = function(data) {
      if (res.statusCode < 400) {
        const userId = req.user?.id || null;
        const ipAddress = req.ip || req.connection.remoteAddress;
        
        db.run(
          'INSERT INTO activity_logs (user_id, action, module, record_id, details, ip_address) VALUES (?, ?, ?, ?, ?, ?)',
          [userId, action, module, recordId, JSON.stringify(details), ipAddress]
        );
      }
      
      originalSend.call(this, data);
    };
    
    next();
  };
};

module.exports = { logActivity };
