const pool = require('../config/db');

class Reaction {
    static async getByPostId(postId) {
        const [rows] = await pool.query('SELECT * FROM reactions WHERE post_id = ?', [postId]);
        return rows;
    }

    static async getAll() {
        const [rows] = await pool.query('SELECT * FROM reactions');
        return rows;
    }

    static async react(userId, postId, reactionType) {
        // Check if reaction already exists
        const [existing] = await pool.query(
            'SELECT * FROM reactions WHERE user_id = ? AND post_id = ?',
            [userId, postId]
        );

        if (existing.length > 0) {
            // Update existing reaction
            const [result] = await pool.query(
                'UPDATE reactions SET reaction_type = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND post_id = ?',
                [reactionType, userId, postId]
            );
            return result;
        } else {
            // Create new reaction
            const [result] = await pool.query(
                'INSERT INTO reactions (user_id, post_id, reaction_type) VALUES (?, ?, ?)',
                [userId, postId, reactionType]
            );
            return result;
        }
    }

    static async delete(userId, postId) {
        const [result] = await pool.query(
            'DELETE FROM reactions WHERE user_id = ? AND post_id = ?',
            [userId, postId]
        );
        return result;
    }

    // Optional: Get reaction count by type for a post
    static async getReactionCounts(postId) {
        const [rows] = await pool.query(
            'SELECT reaction_type, COUNT(*) as count FROM reactions WHERE post_id = ? GROUP BY reaction_type',
            [postId]
        );
        return rows;
    }
}

module.exports = Reaction;