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

module.exports = {
    get_all(req, res, next) {
        let param = {
            order: ['type']
        };
        if (req.query.type) {
            param.where = {
                type: req.query.type
            };
        }
        req.person.getPhones(param)
        .then(p => {
            if (!p) {
                throw {status: 404, message: "Pas de tel"}
            }
            res.json(p)
        })
        .catch(function(error) {
            next(error);
        })
    },
    create(req, res, next) {
        if (!req.body.number || !req.body.type) {
            throw {status: 400, message: "Manque type ou tel"}
        }
        req.person.createPhone({number: req.body.number, type: req.body.type})
        .then (p => {
            res.json(p);
        })
        .catch(error => {
            next(error);
        })
    },
    get_by_id(req, res, next) {
        req.person.getPhones({where: {
            id: req.params.phone_id
        }})
        .then (([p]) => {
            if (!p) {
                throw {status: 404, message: "Pas trouvé"}
            }
            res.json([p]);
        })
        .catch(error => {
            next(error);
        })
    },
    update_by_id(req, res, next) {
        req.person.getPhones({where: {
            id: req.params.phone_id
        }})
        .then (([p]) => {
            if (!p) {
                throw {status: 404, message: "Pas trouvé 2"}
            }
            p.update(req.body);
            res.json([p]);
        })
        .catch(error => {
            next(error);
        })
    },
    delete_by_id(req, res ,next) {
        req.person.getPhones({where: {
            id: req.params.phone_id
        }})
        .then (([p]) => {
            if (!p) {
                throw {status: 404, message: "Pas trouvé 3"}
            }
            p.destroy();
            res.send("fait");
        })
        .catch(error => {
            next(error);
        })
    }
}