const { logActivity, getIpAddress, getUserAgent, getActivityDescription } = require("../utils/activityLogger");

/**
 * Middleware to automatically log activities for specific routes
 * This middleware should be applied AFTER the main route handler
 * Use it by wrapping your route handler with logActivityMiddleware
 */
const createActivityLogMiddleware = (entityType, actionType = null) => {
  return async (req, res, next) => {
    // Store original res.json to intercept response
    const originalJson = res.json.bind(res);

    res.json = function (data) {
      // Only log if request was successful (2xx status)
      if (res.statusCode >= 200 && res.statusCode < 300) {
        // Determine action based on HTTP method if not provided
        let action = actionType;
        if (!action) {
          const methodActionMap = {
            POST: "create",
            PUT: "update",
            PATCH: "edit",
            DELETE: "delete",
            GET: "view",
          };
          action = methodActionMap[req.method] || "unknown";
        }

        // Extract entity ID from various sources
        let entityId = null;
        if (req.params.id) {
          entityId = parseInt(req.params.id);
        } else if (data && data.id) {
          entityId = data.id;
        } else if (data && data.data && data.data.id) {
          entityId = data.data.id;
        }

        // Create description
        const description = getActivityDescription(action, entityType, {
          details: data?.message || data?.title || data?.name,
        });

        // Log the activity (don't await to avoid blocking response)
        if (req.user) {
          logActivity({
            userId: req.user.id,
            companyId: req.user.companyId || null,
            projectId: req.query.projectId || req.body.projectId || null,
            action,
            entityType,
            entityId,
            description,
            metadata: {
              method: req.method,
              path: req.path,
              query: req.query,
              statusCode: res.statusCode,
            },
            ipAddress: getIpAddress(req),
            userAgent: getUserAgent(req),
          }).catch((err) => {
            console.error("Failed to log activity:", err);
          });
        }
      }

      // Call original res.json
      return originalJson(data);
    };

    next();
  };
};

/**
 * Manual activity logger helper for use in controllers
 * @param {Object} req - Express request object
 * @param {string} action - Action performed
 * @param {string} entityType - Type of entity
 * @param {number} entityId - ID of entity
 * @param {string} description - Description of action
 * @param {Object} metadata - Additional metadata
 */
const logActivityManual = async (req, action, entityType, entityId, description, metadata = {}) => {
  if (!req.user) return;

  try {
    await logActivity({
      userId: req.user.id,
      companyId: req.user.companyId || null,
      projectId: req.query.projectId || req.body.projectId || null,
      action,
      entityType,
      entityId,
      description,
      metadata: {
        method: req.method,
        path: req.path,
        ...metadata,
      },
      ipAddress: getIpAddress(req),
      userAgent: getUserAgent(req),
    });
  } catch (error) {
    console.error("Failed to log activity:", error);
  }
};

module.exports = {
  createActivityLogMiddleware,
  logActivityManual,
};
