const logger = require('../config/logger');

/**
 * Admin Operation Logger Middleware
 * Logs all admin operations for audit purposes
 */

/**
 * Log admin operations
 * Records admin actions for audit trail
 */
const logAdminOperation = (req, res, next) => {
  // Store original send function
  const originalSend = res.send;

  // Override send function to capture response
  res.send = function (data) {
    // Restore original send
    res.send = originalSend;

    // Log the operation
    if (req.admin) {
      const logData = {
        timestamp: new Date().toISOString(),
        adminId: req.admin.id,
        adminUsername: req.admin.username,
        adminRole: req.admin.role,
        method: req.method,
        path: req.path,
        url: req.originalUrl,
        ipAddress: req.ip || req.connection.remoteAddress,
        userAgent: req.headers['user-agent'],
        statusCode: res.statusCode,
        requestBody: sanitizeRequestBody(req.body),
        query: req.query,
      };

      // Log based on status code
      if (res.statusCode >= 400) {
        logger.warn('Admin operation failed:', logData);
      } else {
        logger.info('Admin operation:', logData);
      }
    }

    // Send the response
    return originalSend.call(this, data);
  };

  next();
};

/**
 * Sanitize request body to remove sensitive data
 * @param {Object} body - Request body
 * @returns {Object} Sanitized body
 */
const sanitizeRequestBody = (body) => {
  if (!body || typeof body !== 'object') {
    return body;
  }

  const sanitized = { ...body };
  
  // Remove sensitive fields
  const sensitiveFields = ['password', 'token', 'secret', 'apiKey', 'creditCard'];
  
  sensitiveFields.forEach(field => {
    if (sanitized[field]) {
      sanitized[field] = '[REDACTED]';
    }
  });

  return sanitized;
};

module.exports = {
  logAdminOperation,
};
