/**
 * Comment Model
 * Handles task comment operations
 */

const { query } = require("../config/database");

class Comment {
  /**
   * Find comment by ID
   */
  static async findById(id) {
    const comments = await query(
      `SELECT c.*, 
                    u.username,
                    CONCAT(e.first_name, ' ', e.last_name) as author_name,
                    e.profile_image as author_image
             FROM task_comments c
             LEFT JOIN users u ON c.user_id = u.id
             LEFT JOIN employees e ON u.employee_id = e.id
             WHERE c.id = ?`,
      [id],
    );
    return comments[0] || null;
  }

  /**
   * Create new comment
   */
  static async create(commentData) {
    const result = await query(
      `INSERT INTO task_comments (task_id, user_id, comment)
             VALUES (?, ?, ?)`,
      [commentData.taskId, commentData.userId, commentData.comment],
    );

    return this.findById(result.insertId);
  }

  /**
   * Update comment
   */
  static async update(id, comment) {
    await query("UPDATE task_comments SET comment = ? WHERE id = ?", [
      comment,
      id,
    ]);
    return this.findById(id);
  }

  /**
   * Delete comment
   */
  static async delete(id) {
    await query("DELETE FROM task_comments WHERE id = ?", [id]);
    return true;
  }

  /**
   * Get comments by task
   */
  static async findByTask(taskId) {
    return query(
      `SELECT c.*, 
                    u.username,
                    u.role as user_role,
                    CONCAT(e.first_name, ' ', e.last_name) as author_name,
                    e.profile_image as author_image
             FROM task_comments c
             LEFT JOIN users u ON c.user_id = u.id
             LEFT JOIN employees e ON u.employee_id = e.id
             WHERE c.task_id = ?
             ORDER BY c.created_at DESC`,
      [taskId],
    );
  }
}

module.exports = Comment;
