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

module.exports = {
    get_all(req, res, next) {
        let param = {
            order: ['lastname']
        };
        if (req.query.lastname) {
            param.where = {
                lastname: req.query.lastname
            };
        }
        db.Person.findAll(param).then(persons => {
            res.json(persons)
        }) .catch(error => {
            next(error);
        })
    },

    create(req, res, next) {
        if (req.body.firstname == undefined || req.body.lastname == undefined) {
            throw "Un des éléments est vide";
        }
        return db.Person.create({lastname: req.body.lastname, firstname: req.body.firstname}).then(p => 
            res.json(p)
        ) .catch(function (error) {
            next(error);
        })  
    },
    get_by_id(req, res, next) {
        db.Person.findByPk(req.params.person_id).then(persons => {
            if (!persons) {
                throw { status: 404, message: "Pas bonne id" }
            }
            res.json(persons)
        }) .catch(function (error) {
            next(error);
        })
    },
    update_by_id(req, res, next) {
        db.Person.findByPk(req.params.person_id).then(person => {
            if (!person) {
                throw "Pas bonne id";
            } else {
                person.update(req.body)
                .then(
                    res.send("ok")
                )
            }
        }) .catch(function (error) {
            next(error);
        })


    },
    delete_by_id(req, res, next) {
        db.Person.destroy({
            where: {
                id: req.params.person_id
            }
        }) .then(data => {
            if (!data) {
                throw "Pas bonne id"
            }
            res.send("fait")}) .catch(function (error) {
            next(error);
        })
    },
    load_by_id(req, res, next) {
        db.Person.findByPk(req.params.person_id).then(person => {
            if (!person) {
                throw { status: 404, message: "Pas bonne id" }
            }
            req.person = person;
            next();
        }) .catch(function (error) {
            next(error);
        })
    }
};