const { JobSafetyAnalysis, Projects, Users } = require("../models");
const { addFormattedIds, addFormattedId } = require("../utils/idFormatter");
const { createJSANotification } = require("../utils/notificationHelper");
const uploadFile = require("../utils/uploadFile");
const { logActivity, getIpAddress, getUserAgent } = require("../utils/activityLogger");

const getJobSafetyAnalyses = async (req, res) => {
  const { projectId } = req.query;

  try {
    const jobSafetyAnalyses = await JobSafetyAnalysis.findAll({
      where: {
        ProjectId: projectId,
      },
      include: [Projects],
    });

    const response = jobSafetyAnalyses.map(({ data, Project, id }) => {
      return {
        ...JSON.parse(data),
        id,
        project: Project.name,
      };
    });

    res.json(addFormattedIds("job-safety-analysis", response));
  } catch (err) {
    res.status(500).json({ message: "Failed to fetch" });
  }
};

const getSingleJobSafetyAnalysis = async (req, res) => {
  const { id } = req.params;

  try {
    const jobSafetyAnalysis = await JobSafetyAnalysis.findByPk(id, {
      include: [Projects],
    });

    if (!jobSafetyAnalysis) {
      return res.status(404).json({ message: "Job safety analysis not found" });
    }

    const responseData = {
      ...JSON.parse(jobSafetyAnalysis.data),
      id: jobSafetyAnalysis.id,
      project: jobSafetyAnalysis.Project.name,
    };

    const response = {
      data: addFormattedId("job-safety-analysis", responseData),
    };

    res.json(response);
  } catch (err) {
    res.status(500).json({ message: "Failed to fetch" });
  }
};

const createJobSafetyAnalysis = async (req, res) => {
  const { projectId } = req.query;

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

  try {
    const filesData = await uploadFile(req.files);
    const data = { ...JSON.parse(req.body.data), ...filesData };

    const createdJSA = await JobSafetyAnalysis.create({
      data: data,
      ProjectId: projectId,
    });

    // Get formatted ID
    const formattedData = addFormattedId("job-safety-analysis", { id: createdJSA.id });

    // Extract contributor user IDs from the data
    // Contributors are stored in the data JSON - adjust based on your actual structure
    const contributorIds = [];
    if (data.contributors) {
      // If contributors is a comma-separated string or array
      if (typeof data.contributors === 'string') {
        // Try to parse if it's a JSON string, or split by comma
        try {
          const parsed = JSON.parse(data.contributors);
          if (Array.isArray(parsed)) {
            contributorIds.push(...parsed.filter(id => typeof id === 'number'));
          }
        } catch {
          // If not JSON, might be comma-separated IDs
          const ids = data.contributors.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
          contributorIds.push(...ids);
        }
      } else if (Array.isArray(data.contributors)) {
        for (const contributor of data.contributors) {
          if (contributor.userId) {
            contributorIds.push(contributor.userId);
          } else if (typeof contributor === 'number') {
            contributorIds.push(contributor);
          }
        }
      }
    }

    // Calculate priority based on highest risk score in sheets
    let notificationPriority = "medium"; // default
    if (data.sheets && Array.isArray(data.sheets)) {
      let maxRiskScore = 0;
      for (const sheet of data.sheets) {
        if (sheet.rows && Array.isArray(sheet.rows)) {
          for (const row of sheet.rows) {
            const likelihood = Number(row.likelihood) || 0;
            const severity = Number(row.severity) || 0;
            const riskScore = likelihood * severity;
            if (riskScore > maxRiskScore) {
              maxRiskScore = riskScore;
            }
          }
        }
      }
      
      // Map risk score to priority
      // Risk score ranges: 1-4 = low, 5-9 = medium, 10-16 = high, 20-25 = urgent
      if (maxRiskScore >= 20) {
        notificationPriority = "urgent";
      } else if (maxRiskScore >= 10) {
        notificationPriority = "high";
      } else if (maxRiskScore >= 5) {
        notificationPriority = "medium";
      } else {
        notificationPriority = "low";
      }
    }

    // Create notifications for all contributors
    if (contributorIds.length > 0) {
      await createJSANotification({
        userIds: contributorIds,
        assignedBy: req.user.id,
        companyId: req.user.companyId,
        projectId: projectId,
        jsaId: createdJSA.id,
        taskActivity: data.task_activity || "Job Safety Analysis",
        formattedId: formattedData.formattedId,
        priority: notificationPriority,
      });
    }

    // Log job safety analysis creation activity
    await logActivity({
      userId: req.user.id,
      companyId: req.user.companyId,
      projectId: projectId,
      action: "create",
      entityType: "Job Safety Analysis",
      entityId: createdJSA.id,
      description: `New job safety analysis report created`,
      metadata: {
        jsaId: formattedData.formattedId,
        taskActivity: data.task_activity || "Job Safety Analysis",
      },
      ipAddress: getIpAddress(req),
      userAgent: getUserAgent(req),
    });

    res.status(201).json({ message: "Job safety analysis created successfully" });
  } catch (err) {
    console.error("Error creating job safety analysis:", err);
    res.status(500).json({ message: "Failed to create" });
  }
};

module.exports = {
  getJobSafetyAnalyses,
  getSingleJobSafetyAnalysis,
  createJobSafetyAnalysis,
};
