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

module.exports = {
    get_all(req, res, next) {
        db.Group.findAll()
        .then(g => {
            res.json(g)
        })
        .catch(error => {
            next(error);
        })
    },
    create(req, res, next) {
        if (!req.body.title) {
            throw {status: 400, message: "Titre vide"}
        }
        db.Group.create({title: req.body.title})
        .then (g => {
           res.json(g);
        })
        .catch(error => {
            next(error);
        })
    },
    get_by_id(req, res, next) {
        db.Group.findByPk(req.params.group_id)
        .then(g => {
            if (!g) {
                throw { status: 404, message: "Pas trouvé"}
            }
            res.json(g);
        })
        .catch(error => {
            next(error);
        })
    },
    update_by_id(req, res, next) {
        db.Group.findByPk(req.params.group_id) 
        .then ( g => {
            if (!g) {
                throw { status: 404, message: "Pas trouvé"}
            } else {
                g.update(req.body)
                .then (res.json(g))
            }
        })
        .catch (e => {
            next(e);
        })
    },
    delete_by_id(req, res, next) {
        db.Group.destroy({
            where: {
                id: req.params.group_id
            }
        })
        .then (g => {
            if (!g) {
                throw {status: 404, message: "Pas trouvé"}
            }
            res.send("fait");
        })
        .catch (e => {
            next(e);
        })
    }
}