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

exports.getAllGroups = async (req, res) => {
    const [rows] = await db.query('SELECT * FROM groups');
    res.json(rows);
};

exports.getGroupById = async (req, res) => {
    const [rows] = await db.query('SELECT * FROM groups WHERE id = ?', [req.params.id]);
    if (rows.length === 0) return res.status(404).json({ error: 'Group not found' });
    res.json(rows[0]);
};

exports.createGroup = async (req, res) => {
    const { name } = req.body;
    await db.query('INSERT INTO groups (name) VALUES (?)', [name]);
    res.status(201).json({ message: 'Group created' });
};

exports.updateGroup = async (req, res) => {
    const { name } = req.body;
    await db.query('UPDATE groups SET name = ? WHERE id = ?', [name, req.params.id]);
    res.json({ message: 'Group updated' });
};

exports.deleteGroup = async (req, res) => {
    await db.query('DELETE FROM groups WHERE id = ?', [req.params.id]);
    res.status(204).send();
};

exports.getGroupUsers = async (req, res) => {
    const [rows] = await db.query(`
    SELECT u.* FROM users u
    JOIN group_users gu ON gu.user_id = u.id
    WHERE gu.group_id = ?
  `, [req.params.id]);
    res.json(rows);
};

exports.getGroupCours = async (req, res) => {
    const [rows] = await db.query(`
    SELECT c.* FROM courses c
    JOIN group_cours gc ON gc.cours_id = c.id
    WHERE gc.group_id = ?
  `, [req.params.id]);
    res.json(rows);
};

exports.addUserToGroup = async (req, res) => {
    const { userId } = req.body;
    await db.query('INSERT IGNORE INTO group_users (group_id, user_id) VALUES (?, ?)', [req.params.id, userId]);
    res.status(200).json({ message: 'User added to group' });
};

exports.addCoursToGroup = async (req, res) => {
    const { coursId } = req.body;
    await db.query('INSERT IGNORE INTO group_cours (group_id, cours_id) VALUES (?, ?)', [req.params.id, coursId]);
    res.status(200).json({ message: 'Cours added to group' });
};

exports.removeUserFromGroup = async (req, res) => {
    await db.query('DELETE FROM group_users WHERE group_id = ? AND user_id = ?', [req.params.id, req.params.userId]);
    res.status(204).send();
};

exports.removeCoursFromGroup = async (req, res) => {
    await db.query('DELETE FROM group_courses WHERE group_id = ? AND course_id = ?', [req.params.id, req.params.courseId]);
    res.status(204).send();
};
