import { pool } from '../../config/db.js'; export async function findByEntity(entityType, entityId) { const [rows] = await pool.query( `SELECT c.id, c.entity_type, c.entity_id, c.user_id, u.name AS user_name, c.message, c.edit_version, c.created_at, c.updated_at FROM comments c JOIN users u ON u.id = c.user_id WHERE c.entity_type = ? AND c.entity_id = ? ORDER BY c.created_at`, [entityType, entityId] ); return rows; } export async function findById(id) { const [rows] = await pool.query( `SELECT c.id, c.entity_type, c.entity_id, c.user_id, u.name AS user_name, c.message, c.edit_version, c.created_at, c.updated_at FROM comments c JOIN users u ON u.id = c.user_id WHERE c.id = ?`, [id] ); return rows[0] || null; } export async function update(id, message, editVersion) { const [result] = await pool.query('UPDATE comments SET message = ?, edit_version = edit_version + 1 WHERE id = ? AND edit_version = ?', [message, id, editVersion]); return result.affectedRows ? findById(id) : null; } export async function remove(id) { await pool.query('DELETE FROM comments WHERE id = ?', [id]); } // Usado al borrar la entidad duena (actividad, proyecto): limpia sus comentarios de paso, ya que // no hay FK fisica cruzada (entity_type/entity_id es polimorfico) que lo haga por cascada. export async function removeByEntity(entityType, entityId) { await pool.query('DELETE FROM comments WHERE entity_type = ? AND entity_id = ?', [entityType, entityId]); } // Usado al convertir una actividad en proyecto: sus comentarios pasan a la actividad nueva que // hereda sus tareas, en vez de perderse cuando se borra la actividad original. export async function reassignEntity(entityType, oldEntityId, newEntityId) { await pool.query('UPDATE comments SET entity_id = ? WHERE entity_type = ? AND entity_id = ?', [newEntityId, entityType, oldEntityId]); } export async function create({ entityType, entityId, userId, message }) { const [result] = await pool.query( 'INSERT INTO comments (entity_type, entity_id, user_id, message) VALUES (?, ?, ?, ?)', [entityType, entityId, userId, message] ); return findById(result.insertId); }