const { ActivityLog } = require("../models");

/**
 * Log user activity
 * @param {Object} params - Activity parameters
 * @param {number} params.userId - User ID
 * @param {number} params.companyId - Company ID (optional)
 * @param {number} params.projectId - Project ID (optional)
 * @param {string} params.action - Action performed (create, edit, delete, view, etc.)
 * @param {string} params.entityType - Type of entity (Deviations, Site Monitoring, etc.)
 * @param {number} params.entityId - ID of the entity (optional)
 * @param {string} params.description - Human-readable description
 * @param {Object} params.metadata - Additional metadata (optional)
 * @param {string} params.ipAddress - IP address (optional)
 * @param {string} params.userAgent - User agent (optional)
 * @returns {Promise<ActivityLog>}
 */
const logActivity = async ({
  userId,
  companyId = null,
  projectId = null,
  action,
  entityType,
  entityId = null,
  description,
  metadata = null,
  ipAddress = null,
  userAgent = null,
}) => {
  try {
    const activityLog = await ActivityLog.create({
      userId,
      companyId,
      projectId,
      action,
      entityType,
      entityId,
      description,
      metadata,
      ipAddress,
      userAgent,
    });

    return activityLog;
  } catch (error) {
    console.error("Error logging activity:", error);
    // Don't throw error - activity logging should not break the main flow
    return null;
  }
};

/**
 * Get activity description based on action and entity type
 * @param {string} action - Action performed
 * @param {string} entityType - Type of entity
 * @param {Object} data - Additional data for description
 * @returns {string}
 */
const getActivityDescription = (action, entityType, data = {}) => {
  const actionMap = {
    create: "created",
    edit: "edited",
    update: "updated",
    delete: "deleted",
    view: "viewed",
    assign: "assigned",
    complete: "completed",
    approve: "approved",
    reject: "rejected",
  };

  const actionText = actionMap[action] || action;
  
  if (data.details) {
    return `${actionText} ${entityType}: ${data.details}`;
  }
  
  return `${actionText} ${entityType}`;
};

/**
 * Extract IP address from request
 * @param {Object} req - Express request object
 * @returns {string}
 */
const getIpAddress = (req) => {
  return (
    req.headers["x-forwarded-for"]?.split(",")[0] ||
    req.headers["x-real-ip"] ||
    req.connection?.remoteAddress ||
    req.socket?.remoteAddress ||
    req.ip ||
    "unknown"
  );
};

/**
 * Extract user agent from request
 * @param {Object} req - Express request object
 * @returns {string}
 */
const getUserAgent = (req) => {
  return req.headers["user-agent"] || "unknown";
};

module.exports = {
  logActivity,
  getActivityDescription,
  getIpAddress,
  getUserAgent,
};
