const {
  Reports,
  Projects,
  SafetyTools,
  ActivityLog,
  Users,
  RiskAssessment,
  JobSafetyAnalysis,
  PermitToWork,
  HazopStudy,
} = require("../models");
const { Op } = require("sequelize");

const getDashboardAnalytics = async (req, res) => {
  const { projectId, startDate, endDate } = req.query;

  if (!projectId) {
    return res.status(400).json({ message: "Project ID is required" });
  }

  try {
    const project = await Projects.findByPk(projectId);
    if (!project) {
      return res.status(404).json({ message: "Project not found" });
    }

    if (project.CompanyId !== req.user.companyId) {
      return res.status(403).json({ message: "Access denied to this project" });
    }

    // Parse date range - if not provided, use current month
    const now = new Date();
    const currentPeriodStart = startDate 
      ? new Date(startDate) 
      : new Date(now.getFullYear(), now.getMonth(), 1);
    const currentPeriodEnd = endDate 
      ? new Date(endDate) 
      : new Date();
    
    // Ensure end date includes the full day
    currentPeriodEnd.setHours(23, 59, 59, 999);

    // Calculate previous period (same duration as current period)
    const periodDuration = currentPeriodEnd - currentPeriodStart;
    const lastPeriodEnd = new Date(currentPeriodStart.getTime() - 1); // 1ms before current period
    const lastPeriodStart = new Date(lastPeriodEnd.getTime() - periodDuration);
    
    // Set last period start to beginning of day
    lastPeriodStart.setHours(0, 0, 0, 0);

    // Calculate weeks based on the selected date range
    const totalDays = Math.ceil((currentPeriodEnd - currentPeriodStart) / (1000 * 60 * 60 * 24)) + 1;
    const numberOfWeeks = Math.min(Math.ceil(totalDays / 7), 4); // Max 4 weeks
    
    const weeks = [];
    const currentDate = new Date(currentPeriodStart);
    let weekNumber = 1;

    while (currentDate <= currentPeriodEnd && weekNumber <= numberOfWeeks) {
      const weekStart = new Date(currentDate);
      const weekEnd = new Date(currentDate);
      weekEnd.setDate(weekEnd.getDate() + 6);

      if (weekEnd > currentPeriodEnd) {
        weekEnd.setTime(currentPeriodEnd.getTime());
      }

      weeks.push({
        weekNumber,
        start: weekStart,
        end: weekEnd,
      });

      currentDate.setDate(currentDate.getDate() + 7);
      weekNumber++;
    }

    const getEntityPeriodStats = async (Model, title, extraWhere = {}) => {
      const currentPeriodTotal = await Model.count({
        where: {
          ProjectId: projectId,
          ...extraWhere,
          createdAt: {
            [Op.gte]: currentPeriodStart,
            [Op.lte]: currentPeriodEnd,
          },
        },
      });

      const lastPeriodTotal = await Model.count({
        where: {
          ProjectId: projectId,
          ...extraWhere,
          createdAt: {
            [Op.gte]: lastPeriodStart,
            [Op.lte]: lastPeriodEnd,
          },
        },
      });

      let percentageChange = 0;
      if (lastPeriodTotal > 0) {
        percentageChange = Math.round(
          ((currentPeriodTotal - lastPeriodTotal) / lastPeriodTotal) * 100,
        );
      } else if (currentPeriodTotal > 0) {
        percentageChange = 100;
      }

      const weeklyData = await Promise.all(
        weeks.map(async (week) => {
          const count = await Model.count({
            where: {
              ProjectId: projectId,
              ...extraWhere,
              createdAt: {
                [Op.gte]: week.start,
                [Op.lte]: week.end,
              },
            },
          });

          return {
            week: week.weekNumber,
            count,
            percentage:
              currentPeriodTotal > 0
                ? Math.round((count / currentPeriodTotal) * 100)
                : 0,
          };
        }),
      );

      return {
        title,
        total: currentPeriodTotal,
        percentageChange,
        data: weeklyData.map((week) => ({
          name: `Week${week.week}`,
          value: week.percentage,
          count: week.count,
        })),
      };
    };

    const getReportStats = async (reportType) => {
      const currentPeriodTotal = await Reports.count({
        where: {
          ProjectId: projectId,
          type: reportType,
          createdAt: {
            [Op.gte]: currentPeriodStart,
            [Op.lte]: currentPeriodEnd,
          },
        },
      });

      const lastPeriodTotal = await Reports.count({
        where: {
          ProjectId: projectId,
          type: reportType,
          createdAt: {
            [Op.gte]: lastPeriodStart,
            [Op.lte]: lastPeriodEnd,
          },
        },
      });

      let percentageChange = 0;
      if (lastPeriodTotal > 0) {
        percentageChange = Math.round(
          ((currentPeriodTotal - lastPeriodTotal) / lastPeriodTotal) * 100,
        );
      } else if (currentPeriodTotal > 0) {
        percentageChange = 100;
      }

      const weeklyData = await Promise.all(
        weeks.map(async (week) => {
          const count = await Reports.count({
            where: {
              ProjectId: projectId,
              type: reportType,
              createdAt: {
                [Op.gte]: week.start,
                [Op.lte]: week.end,
              },
            },
          });

          return {
            week: week.weekNumber,
            count,
            percentage:
              currentPeriodTotal > 0
                ? Math.round((count / currentPeriodTotal) * 100)
                : 0,
          };
        }),
      );

      return {
        total: currentPeriodTotal,
        percentageChange,
        weeklyData,
      };
    };

    const [
      deviations,
      siteMonitoring,
      casesInvestigations,
      permitToWork,
      hazop,
      riskAssessment,
      jsa,
      toolboxTalk,
      checklist,
    ] = await Promise.all([
      getReportStats("deviations"),
      getReportStats("site-monitoring"),
      getReportStats("case-investigations"),
      getEntityPeriodStats(PermitToWork, "Permit to Work"),
      getEntityPeriodStats(HazopStudy, "HAZOP/HAZID"),
      getEntityPeriodStats(RiskAssessment, "Risk Assessment"),
      getEntityPeriodStats(JobSafetyAnalysis, "JSA"),
      getEntityPeriodStats(SafetyTools, "Toolbox talk", {
        toolType: { [Op.in]: ["toolbox-talk", "toolbox-meeting"] },
      }),
      getEntityPeriodStats(SafetyTools, "Checklist", {
        toolType: "pre-task-checklist",
      }),
    ]);

    const response = {
      deviations: {
        title: "Deviations",
        total: deviations.total,
        percentageChange: deviations.percentageChange,
        data: deviations.weeklyData.map((week) => ({
          name: `Week${week.week}`,
          value: week.percentage,
          count: week.count,
        })),
      },
      siteMonitoring: {
        title: "Site Monitoring",
        total: siteMonitoring.total,
        percentageChange: siteMonitoring.percentageChange,
        count: siteMonitoring.total,
        trend: siteMonitoring.percentageChange >= 0 ? "up" : "down",
        data: siteMonitoring.weeklyData.map((week) => ({
          name: `Week${week.week}`,
          value: week.percentage,
          count: week.count,
        })),
      },
      casesInvestigations: {
        title: "Cases Investigations",
        total: casesInvestigations.total,
        count: casesInvestigations.total,
        percentageChange: casesInvestigations.percentageChange,
        trend: casesInvestigations.percentageChange >= 0 ? "up" : "down",
        data: casesInvestigations.weeklyData.map((week) => ({
          name: `Week${week.week}`,
          value: week.percentage,
          count: week.count,
        })),
      },
      permitToWork,
      hazop,
      riskAssessment,
      jsa,
      toolboxTalk,
      checklist,
      dateRange: {
        currentPeriod: {
          start: currentPeriodStart.toISOString(),
          end: currentPeriodEnd.toISOString(),
        },
        lastPeriod: {
          start: lastPeriodStart.toISOString(),
          end: lastPeriodEnd.toISOString(),
        },
        totalDays: totalDays,
      },
    };

    res.json(response);
  } catch (error) {
    console.error("Error fetching dashboard analytics:", error);
    res.status(500).json({ message: "Failed to fetch dashboard analytics" });
  }
};

/**
 * Get statistical reports data for charts
 * Supports filtering by multiple safety tool types and date range
 * Returns data for both line chart and bar chart with separate data for each tool type
 */
const getStatisticalReports = async (req, res) => {
  const { projectId, startDate, endDate, toolTypes } = req.query;

  if (!projectId) {
    return res.status(400).json({ message: "Project ID is required" });
  }

  try {
    const project = await Projects.findByPk(projectId);
    if (!project) {
      return res.status(404).json({ message: "Project not found" });
    }

    if (project.CompanyId !== req.user.companyId) {
      return res.status(403).json({ message: "Access denied to this project" });
    }

    // Parse tool types (can be comma-separated string or array)
    let selectedToolTypes = [];
    if (toolTypes) {
      selectedToolTypes = Array.isArray(toolTypes) 
        ? toolTypes 
        : toolTypes.split(',').map(t => t.trim());
    }

    // If no tool types selected, return empty data
    if (selectedToolTypes.length === 0) {
      return res.json({
        lineChartData: [],
        barChartData: [],
        toolTypesData: [],
        dateRange: {
          start: new Date().toISOString(),
          end: new Date().toISOString(),
          totalDays: 0,
        },
        summary: {
          totalTools: 0,
          totalReports: 0,
        },
      });
    }

    // Validate tool types
    const validToolTypes = [
      "job-safety-analysis",
      "risk-assessment",
      "toolbox-meeting",
      "pre-task-checklist",
      "permit-to-work",
      "hazop",
      "equipment-controller",
      // Legacy values for backward compatibility
      "toolbox-talk",
      "equipment-control",
    ];
    
    const invalidTypes = selectedToolTypes.filter(t => !validToolTypes.includes(t));
    if (invalidTypes.length > 0) {
      return res.status(400).json({
        message: `Invalid tool types: ${invalidTypes.join(", ")}. Must be one of: ${validToolTypes.join(", ")}`,
      });
    }

    // Normalize tool types (map legacy names to new names for querying)
    const normalizeToolType = (type) => {
      const mapping = {
        "toolbox-talk": "toolbox-meeting",
        "equipment-control": "equipment-controller",
      };
      return mapping[type] || type;
    };

    // For database query, we need to include both new and legacy names
    const dbToolTypes = selectedToolTypes.flatMap(type => {
      const normalized = normalizeToolType(type);
      // Return both the normalized and original if they're different
      if (normalized !== type) {
        return [type, normalized];
      }
      // Also include legacy equivalents
      if (type === "toolbox-meeting") return [type, "toolbox-talk"];
      if (type === "equipment-controller") return [type, "equipment-control"];
      return [type];
    });

    // Remove duplicates
    const uniqueDbToolTypes = [...new Set(dbToolTypes)];

    // Parse date range
    const start = startDate
      ? new Date(startDate)
      : new Date(new Date().getFullYear(), new Date().getMonth(), 1);
    const end = endDate ? new Date(endDate) : new Date();

    // Ensure end date includes the full day
    end.setHours(23, 59, 59, 999);

    // Calculate total days in range
    const totalDays = Math.ceil((end - start) / (1000 * 60 * 60 * 24)) + 1;

    // Build where clause for safety tools - MULTIPLE tool types
    const whereClause = {
      ProjectId: projectId,
      toolType: {
        [Op.in]: uniqueDbToolTypes, // Include both new and legacy tool type names
      },
      createdAt: {
        [Op.gte]: start,
        [Op.lte]: end,
      },
    };

    // Fetch all safety tools in the date range for selected tool types
    const safetyTools = await SafetyTools.findAll({
      where: whereClause,
      attributes: ["id", "toolType", "data", "createdAt"],
      order: [["createdAt", "ASC"]],
    });

    // Fetch Risk Assessment data if selected
    let riskAssessments = [];
    if (selectedToolTypes.includes("risk-assessment")) {
      riskAssessments = await RiskAssessment.findAll({
        where: {
          ProjectId: projectId,
          createdAt: {
            [Op.gte]: start,
            [Op.lte]: end,
          },
        },
        attributes: ["id", "data", "createdAt"],
        order: [["createdAt", "ASC"]],
      });
      
      // Transform Risk Assessment to match SafetyTools format
      riskAssessments = riskAssessments.map(ra => ({
        id: ra.id,
        toolType: "risk-assessment",
        data: ra.data,
        createdAt: ra.createdAt,
      }));
    }

    // Fetch Job Safety Analysis data if selected
    let jobSafetyAnalyses = [];
    if (selectedToolTypes.includes("job-safety-analysis")) {
      jobSafetyAnalyses = await JobSafetyAnalysis.findAll({
        where: {
          ProjectId: projectId,
          createdAt: {
            [Op.gte]: start,
            [Op.lte]: end,
          },
        },
        attributes: ["id", "data", "createdAt"],
        order: [["createdAt", "ASC"]],
      });
      
      // Transform Job Safety Analysis to match SafetyTools format
      jobSafetyAnalyses = jobSafetyAnalyses.map(jsa => ({
        id: jsa.id,
        toolType: "job-safety-analysis",
        data: jsa.data,
        createdAt: jsa.createdAt,
      }));
    }

    let permitToWorkRows = [];
    if (selectedToolTypes.includes("permit-to-work")) {
      permitToWorkRows = await PermitToWork.findAll({
        where: {
          ProjectId: projectId,
          createdAt: {
            [Op.gte]: start,
            [Op.lte]: end,
          },
        },
        attributes: ["id", "data", "createdAt"],
        order: [["createdAt", "ASC"]],
      });
      permitToWorkRows = permitToWorkRows.map((p) => ({
        id: p.id,
        toolType: "permit-to-work",
        data: p.data,
        createdAt: p.createdAt,
      }));
    }

    let hazopRows = [];
    if (selectedToolTypes.includes("hazop")) {
      hazopRows = await HazopStudy.findAll({
        where: {
          ProjectId: projectId,
          createdAt: {
            [Op.gte]: start,
            [Op.lte]: end,
          },
        },
        attributes: ["id", "data", "createdAt"],
        order: [["createdAt", "ASC"]],
      });
      hazopRows = hazopRows.map((h) => ({
        id: h.id,
        toolType: "hazop",
        data: h.data,
        createdAt: h.createdAt,
      }));
    }

    // Combine safety tools, risk assessments, job safety analyses, PTW, HAZOP
    const allTools = [
      ...safetyTools,
      ...riskAssessments,
      ...jobSafetyAnalyses,
      ...permitToWorkRows,
      ...hazopRows,
    ];

    // Helper function to extract hours from safety tool data
    const extractHours = (toolData) => {
      try {
        const parsed =
          typeof toolData === "string" ? JSON.parse(toolData) : toolData;

        // Look for common hour fields in the data
        const hourFields = ["hours", "duration", "time_spent", "work_hours"];

        for (const field of hourFields) {
          if (parsed[field] !== undefined) {
            const hours = parseFloat(parsed[field]);
            if (!isNaN(hours)) {
              return hours;
            }
          }
        }

        // Default to 1 hour if no hour field found
        return 1;
      } catch (error) {
        return 1;
      }
    };

    // Generate day labels (every 2 days for 30 days)
    const dayLabels = [];
    for (let i = 1; i <= Math.min(totalDays, 30); i += 2) {
      dayLabels.push(String(i).padStart(2, "0"));
    }

    // Tool type display names and colors
    const toolTypeConfig = {
      "job-safety-analysis": { name: "JSA", color: "#0B3558" },
      "risk-assessment": { name: "Risk Assessment", color: "#1BB489" },
      "toolbox-meeting": { name: "Toolbox Talk", color: "#3B6594" },
      "pre-task-checklist": { name: "Checklist", color: "#9E0D0D" },
      "permit-to-work": { name: "PTW", color: "#172E4E" },
      "hazop": { name: "HAZOP/HAZID", color: "#36D399" },
      "equipment-controller": { name: "Equipment Control", color: "#FF9800" },
      // Legacy mappings (map to same config as new names)
      "toolbox-talk": { name: "Toolbox Talk", color: "#3B6594" },
      "equipment-control": { name: "Equipment Control", color: "#FF9800" },
    };

    // Initialize data structures for each tool type
    const lineChartData = {};
    const barChartData = {};
    
    dayLabels.forEach((day) => {
      lineChartData[day] = { day };
      barChartData[day] = { day };
      
      // Initialize each tool type to 0
      selectedToolTypes.forEach((toolType) => {
        const config = toolTypeConfig[toolType];
        lineChartData[day][config.name] = 0;
        barChartData[day][config.name] = 0;
      });
    });

    // Group tools by type for summary
    const toolsByType = {};
    selectedToolTypes.forEach((toolType) => {
      toolsByType[toolType] = {
        tools: [],
        totalHours: 0,
        count: 0,
      };
    });

    // Process each safety tool - COUNT REPORTS INSTEAD OF HOURS
    allTools.forEach((tool) => {
      const toolDate = new Date(tool.createdAt);
      const dayOfMonth = toolDate.getDate();
      const reportCount = 1; // Count 1 report instead of extracting hours
      
      // Normalize tool type for display (map legacy to new)
      let displayToolType = tool.toolType;
      if (tool.toolType === "toolbox-talk") displayToolType = "toolbox-meeting";
      if (tool.toolType === "equipment-control") displayToolType = "equipment-controller";
      // risk-assessment, permit-to-work, hazop stay as is

      const config = toolTypeConfig[displayToolType];

      // Find the closest day label (every 2 days)
      const closestDayLabel = dayLabels.reduce((prev, curr) => {
        const prevDiff = Math.abs(parseInt(prev) - dayOfMonth);
        const currDiff = Math.abs(parseInt(curr) - dayOfMonth);
        return currDiff < prevDiff ? curr : prev;
      });

      // Add to line chart data - COUNT REPORTS
      if (lineChartData[closestDayLabel] && config) {
        lineChartData[closestDayLabel][config.name] += reportCount;
      }

      // Add to bar chart data - COUNT REPORTS
      if (barChartData[closestDayLabel] && config) {
        barChartData[closestDayLabel][config.name] += reportCount;
      }

      // Add to summary (use normalized type)
      if (!toolsByType[displayToolType]) {
        toolsByType[displayToolType] = {
          tools: [],
          totalReports: 0,
          count: 0,
        };
      }
      toolsByType[displayToolType].tools.push(tool);
      toolsByType[displayToolType].totalReports += reportCount;
      toolsByType[displayToolType].count += 1;
    });

    // Convert to arrays and round values
    const lineChartArray = dayLabels.map((day) => {
      const item = lineChartData[day];
      const rounded = { day: item.day };
      selectedToolTypes.forEach((toolType) => {
        const config = toolTypeConfig[toolType];
        rounded[config.name] = item[config.name] || 0; // No rounding needed for counts
      });
      return rounded;
    });

    const barChartArray = dayLabels.map((day) => {
      const item = barChartData[day];
      const rounded = { day: item.day };
      selectedToolTypes.forEach((toolType) => {
        const config = toolTypeConfig[toolType];
        rounded[config.name] = item[config.name] || 0; // No rounding needed for counts
      });
      return rounded;
    });

    // Prepare tool types data for frontend
    const toolTypesData = selectedToolTypes.map((toolType) => {
      const config = toolTypeConfig[toolType];
      const data = toolsByType[toolType];
      return {
        type: toolType,
        name: config.name,
        color: config.color,
        count: data.count,
        totalReports: data.totalReports,
      };
    });

    const response = {
      lineChartData: lineChartArray,
      barChartData: barChartArray,
      toolTypesData: toolTypesData,
      dateRange: {
        start: start.toISOString(),
        end: end.toISOString(),
        totalDays,
      },
      summary: {
        totalTools: allTools.length,
        totalReports: allTools.length, // Total number of reports
      },
    };

    res.json(response);
  } catch (error) {
    console.error("Error fetching statistical reports:", error);
    res.status(500).json({ message: "Failed to fetch statistical reports" });
  }
};

/**
 * Get last updates (activity logs)
 * ONLY VISIBLE TO SUPER ADMINS
 * Shows recent activities with detailed information including status changes
 * ONLY SHOWS REPORT-RELATED ACTIVITIES (not user authentication)
 */
const getLastUpdates = async (req, res) => {
  try {
    // Check if user is super admin
    if (req.user.role !== "super-admin") {
      return res.status(403).json({
        message: "Access denied. This feature is only available to super admins.",
      });
    }

    const { limit = 10, days = 7, companyId, projectId, userId, action, entityType } = req.query;

    // Calculate date range (default: last 7 days)
    const dateLimit = new Date();
    dateLimit.setDate(dateLimit.getDate() - parseInt(days));

    // ONLY INCLUDE REPORT-RELATED ENTITY TYPES
    const reportEntityTypes = [
      "Deviations",
      "Case Investigation",
      "Site Monitoring",
      "Safety Tools",
      "Toolbox Meeting",
      "Pre-Task Checklist",
      "Equipment Control",
      "Minutes of Meeting",
      "Risk Assessment",
      "Job Safety Analysis",
    ];

    // Build where clause
    const whereClause = {
      createdAt: {
        [Op.gte]: dateLimit,
      },
      // FILTER: Only show report-related activities
      entityType: {
        [Op.in]: entityType ? [entityType] : reportEntityTypes,
      },
      // CRITICAL: Super admin can ONLY see activities from their own company
      companyId: req.user.companyId,
    };

    // Note: companyId filter is now MANDATORY based on logged-in user's company
    // This ensures data isolation between companies

    // Filter by project if provided
    if (projectId) {
      whereClause.projectId = projectId;
    }

    // Filter by user if provided
    if (userId) {
      whereClause.userId = userId;
    }

    // Filter by action if provided
    if (action) {
      whereClause.action = action;
    }

    // Check if ActivityLog table exists, if not return empty data
    let activities = [];
    try {
      // Fetch activity logs
      activities = await ActivityLog.findAll({
        where: whereClause,
        include: [
          {
            model: Users,
            attributes: ["id", "fullname", "email", "role"],
            required: true,
            // SECURITY: Only include users from the same company
            where: {
              CompanyId: req.user.companyId,
            },
          },
          {
            model: Projects,
            attributes: ["id", "name"],
            required: false,
            // SECURITY: Only include projects from the same company
            where: {
              CompanyId: req.user.companyId,
            },
          },
        ],
        order: [["createdAt", "DESC"]], // Newest first
        limit: parseInt(limit),
      });
    } catch (dbError) {
      // If table doesn't exist, return empty data
      console.warn("Activity logs table may not exist:", dbError.message);
      return res.json({
        activities: [],
        summary: {
          totalActivities: 0,
          dateRange: {
            from: dateLimit.toISOString().split("T")[0],
            to: new Date().toISOString().split("T")[0],
            days: parseInt(days),
          },
          filters: {
            companyId: companyId || null,
            projectId: projectId || null,
            userId: userId || null,
            action: action || null,
            entityType: entityType || null,
          },
          byAction: {},
          byEntityType: {},
        },
        message:
          "Activity logs table not found. Please run the SQL migration script.",
      });
    }

    // Format response
    const formattedActivities = activities.map((activity) => {
      const user = activity.User;
      const project = activity.Project;

      // Get user initials for avatar
      const getInitials = (name) => {
        if (!name) return "U";
        const parts = name.trim().split(" ");
        if (parts.length === 1) return parts[0][0].toUpperCase();
        return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
      };

      // Format time (e.g., "3:00 PM") - Frontend will handle timezone conversion
      const formatTime = (date) => {
        const hours = date.getHours();
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const period = hours >= 12 ? "pm" : "am";
        const displayHours = hours % 12 || 12;
        return `${displayHours}:${minutes} ${period}`;
      };

      // Format date (e.g., "2026-02-19") - Frontend will handle timezone conversion
      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        return `${year}-${month}-${day}`;
      };

      // Determine badge based on action
      const getBadge = (action) => {
        if (action === "create") return "New Report";
        if (action === "status_change") return "Status Change";
        if (action === "edit" || action === "update") return "Report Edit";
        if (action === "assign") return "Assignment";
        return null;
      };

      // Build action description
      let actionDescription = activity.description || "No description available";
      
      // For assignments, include both assigner and assigned user
      let assignerName = null;
      let assignedToName = null;
      if (activity.action === "assign" && activity.metadata) {
        assignerName = activity.metadata.assignedBy || null;
        assignedToName = user.fullname; // The user from userId is the assigned user
        
        // Update description to show both
        if (assignerName && assignedToName) {
          actionDescription = `${assignerName} assigned ${assignedToName} to handle this report`;
        }
      }
      
      // Extract status change from metadata if available
      let statusChange = null;
      if (activity.metadata && activity.metadata.statusChange) {
        statusChange = activity.metadata.statusChange;
      }

      // Format entity type for display
      const formatEntityType = (type) => {
        const typeMap = {
          "Deviations": "Deviation",
          "Site Monitoring": "Site Monitoring",
          "Case Investigation": "Case Investigation",
          "Safety Tools": "Safety Tools",
          "Risk Assessment": "Risk Assessment",
          "Job Safety Analysis": "Job Safety Analysis",
        };
        return typeMap[type] || type;
      };

      return {
        id: activity.id,
        userId: user.id,
        username: user.fullname,
        email: user.email,
        userRole: user.role,
        action: activity.action,
        moduleType: formatEntityType(activity.entityType),
        entityType: activity.entityType,
        entityId: activity.entityId,
        projectName: project ? project.name : "N/A",
        projectId: project ? project.id : null,
        actionDescription: actionDescription,
        statusChange: statusChange,
        assignerName: assignerName, // Who assigned (for assignment actions)
        assignedToName: assignedToName, // Who was assigned (for assignment actions)
        date: formatDate(new Date(activity.createdAt)),
        time: formatTime(new Date(activity.createdAt)),
        timestamp: activity.createdAt,
        avatar: getInitials(user.fullname),
        badge: getBadge(activity.action),
        metadata: activity.metadata,
      };
    });

    // Calculate summary statistics
    const byAction = {};
    const byEntityType = {};
    
    formattedActivities.forEach((activity) => {
      // Count by action
      byAction[activity.action] = (byAction[activity.action] || 0) + 1;
      
      // Count by entity type
      byEntityType[activity.entityType] = (byEntityType[activity.entityType] || 0) + 1;
    });

    const summary = {
      totalActivities: formattedActivities.length,
      dateRange: {
        from: dateLimit.toISOString().split("T")[0],
        to: new Date().toISOString().split("T")[0],
        days: parseInt(days),
      },
      filters: {
        companyId: companyId || null,
        projectId: projectId || null,
        userId: userId || null,
        action: action || null,
        entityType: entityType || null,
      },
      byAction,
      byEntityType,
    };

    res.json({
      activities: formattedActivities,
      summary,
    });
  } catch (error) {
    console.error("Error fetching last updates:", error);
    res.status(500).json({
      message: "Failed to fetch last updates",
      error: error.message,
    });
  }
};

module.exports = {
  getDashboardAnalytics,
  getStatisticalReports,
  getLastUpdates,
};
