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

// POST: Registrar una nueva actividad
exports.addActivity = async (req, res) => {
    const {userId, action, mediaTitle, imageUrl} = req.body;

    if (!userId || !action || !mediaTitle) {
        return res.status(400).json({error: 'Faltan datos requeridos'});
    }

    try {
        await db.execute(
            'INSERT INTO activity_log (userId, action, mediaTitle, imageUrl, timestamp) VALUES (?, ?, ?, ?, NOW())',
            [userId, action, mediaTitle, imageUrl || null]
        );
        res.status(200).json({message: 'Actividad registrada correctamente'});
    } catch (err) {
        console.error('❌ Error al insertar actividad:', err);
        res.status(500).json({error: 'Error al guardar la actividad'});
    }
};

exports.getActivitiesByUser = async (req, res) => {
    const {userId} = req.params;

    try {
        const [rows] = await db.execute(
            `SELECT a.id, a.userId, u.username, a.action, a.mediaTitle, a.imageUrl, a.timestamp
             FROM activity_log a
                      JOIN users u ON a.userId = u.id
             WHERE a.userId = ?
             ORDER BY a.timestamp DESC LIMIT 20`,
            [userId]
        );

        res.status(200).json(rows);
    } catch (err) {
        console.error('❌ Error al obtener actividad:', err);
        res.status(500).json({error: 'Error al obtener historial de actividad'});
    }
};


// GET: Obtener comentarios de una actividad
exports.getCommentsByActivity = async (req, res) => {
    const {activityId} = req.params;

    try {
        const [rows] = await db.execute(
            `SELECT c.text, u.username, u.avatarUrl, c.created_at
             FROM comments c
                      JOIN users u ON c.user_id = u.id
             WHERE c.activity_id = ?
             ORDER BY c.created_at DESC`,
            [activityId]
        );

        res.status(200).json(rows);
    } catch (error) {
        console.error('❌ Error al obtener comentarios:', error);
        res.status(500).json({error: 'Error al obtener comentarios'});
    }
};

exports.postComment = async (req, res) => {
    const {userId, activityId, text} = req.body;

    try {
        await db.execute(
            'INSERT INTO comments (user_id, activity_id, text, created_at) VALUES (?, ?, ?, NOW())',
            [userId, activityId, text]
        );
        res.status(200).json({message: 'Comentario guardado'});
    } catch (error) {
        console.error('❌ Error al guardar comentario:', error);
        if (error.code === 'ER_NO_REFERENCED_ROW_2') {
            res.status(400).json({error: 'El usuario no existe en la base de datos'});
        } else {
            res.status(500).json({error: 'Error al guardar comentario'});
        }
    }
};

// POST: Dar like a una actividad
exports.postLike = async (req, res) => {
    const {userId, activityId} = req.body;
    if (!userId || !activityId) {
        return res.status(400).json({error: 'Faltan datos requeridos'});
    }

    try {
        const [existing] = await db.execute(
            'SELECT id FROM likes WHERE user_id = ? AND activity_id = ?',
            [userId, activityId]
        );

        if (existing.length > 0) {
            return res.status(409).json({message: 'Ya diste like'});
        }

        await db.execute(
            'INSERT INTO likes (user_id, activity_id, created_at) VALUES (?, ?, NOW())',
            [userId, activityId]
        );

        res.status(200).json({message: 'Like registrado'});
    } catch (error) {
        console.error('❌ Error al registrar like:', error);
        res.status(500).json({error: 'Error al registrar like'});
    }
};

// GET: Verificar si el usuario ya dio like
exports.checkLike = async (req, res) => {
    const {userId, activityId} = req.params;
    try {
        const [rows] = await db.execute(
            'SELECT id FROM likes WHERE user_id = ? AND activity_id = ?',
            [userId, activityId]
        );
        res.json({liked: rows.length > 0});
    } catch (err) {
        console.error("Error al verificar like:", err);
        res.status(500).json({error: "Error al verificar like"});
    }
};

// DELETE: Eliminar un like
exports.removeLike = async (req, res) => {
    const { userId, activityId } = req.body;

    if (userId === undefined || activityId === undefined) {
        return res.status(400).json({ error: 'Faltan userId o activityId' });
    }

    try {
        await db.execute(
            'DELETE FROM likes WHERE user_id = ? AND activity_id = ?',
            [userId, activityId]
        );
        res.status(200).json({ message: "Like eliminado" });
    } catch (err) {
        console.error("Error al eliminar like:", err);
        res.status(500).json({ error: "Error al eliminar like" });
    }
};

