/**
 * Comment Controller
 * Handles task comment operations
 */

const Comment = require("../models/Comment");
const Task = require("../models/Task");
const ActivityLog = require("../models/ActivityLog");

/**
 * Get comments for a task
 * GET /api/tasks/:taskId/comments
 */
const getCommentsByTask = async (req, res, next) => {
  try {
    const { taskId } = req.params;

    const task = await Task.findById(taskId);

    if (!task) {
      return res.status(404).json({
        success: false,
        message: "Task not found",
      });
    }

    const comments = await Comment.findByTask(taskId);

    res.json({
      success: true,
      data: comments,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Add comment to task
 * POST /api/tasks/:taskId/comments
 */
const createComment = async (req, res, next) => {
  try {
    const { taskId } = req.params;
    const { comment } = req.body;

    const task = await Task.findById(taskId);

    if (!task) {
      return res.status(404).json({
        success: false,
        message: "Task not found",
      });
    }

    const newComment = await Comment.create({
      taskId: parseInt(taskId),
      userId: req.user.id,
      comment,
    });

    // Log activity
    await ActivityLog.create({
      userId: req.user.id,
      actionType: "COMMENT",
      entityType: "Task",
      entityId: taskId,
      description: `Added comment to task: ${task.title}`,
      ipAddress: req.ip,
      userAgent: req.headers["user-agent"],
    });

    res.status(201).json({
      success: true,
      message: "Comment added successfully",
      data: newComment,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Update comment
 * PUT /api/comments/:id
 */
const updateComment = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { comment } = req.body;

    const existingComment = await Comment.findById(id);

    if (!existingComment) {
      return res.status(404).json({
        success: false,
        message: "Comment not found",
      });
    }

    // Check authorization
    if (existingComment.user_id !== req.user.id && req.user.role !== "Admin") {
      return res.status(403).json({
        success: false,
        message: "Not authorized to update this comment",
      });
    }

    const updatedComment = await Comment.update(id, comment);

    res.json({
      success: true,
      message: "Comment updated successfully",
      data: updatedComment,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Delete comment
 * DELETE /api/comments/:id
 */
const deleteComment = async (req, res, next) => {
  try {
    const { id } = req.params;

    const comment = await Comment.findById(id);

    if (!comment) {
      return res.status(404).json({
        success: false,
        message: "Comment not found",
      });
    }

    // Check authorization
    if (comment.user_id !== req.user.id && req.user.role !== "Admin") {
      return res.status(403).json({
        success: false,
        message: "Not authorized to delete this comment",
      });
    }

    await Comment.delete(id);

    res.json({
      success: true,
      message: "Comment deleted successfully",
    });
  } catch (error) {
    next(error);
  }
};

module.exports = {
  getCommentsByTask,
  createComment,
  updateComment,
  deleteComment,
};
