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.getMailAddresses(param)
        .then (mailAddresses => {
            if (!mailAddresses) {
                throw {status: 404, message: "Pas d'adresse"}
            }
            res.json(mailAddresses)
        })
        .catch(function(error) {
            next(error);
        })
    },
    create(req, res, next) {
        if (!req.body.address || !req.body.type) {
            throw {status: 400, message: "Manque type ou adresse"}
        }
        req.person.createMailAddress({address: req.body.address, type: req.body.type})
        .then (mail => {
            res.json(mail);
        })
        .catch(error => {
            next(error);
        })
    },
    get_by_id(req, res, next) {
        req.person.getMailAddresses({where: {
            id: req.params.mail_address_id
        }})
        .then (([m]) => {
            if (!m) {
                throw {status: 404, message: "Pas trouvé"}
            }
            res.json([m]);
        })
        .catch(error => {
            next(error);
        })
    },
    update_by_id(req, res, next) {
        req.person.getMailAddresses({where: {
            id: req.params.mail_address_id
        }})
        .then (([m]) => {
            if (!m) {
                throw {status: 404, message: "Pas trouvé 2"}
            }
            m.update(req.body);
            res.json(m);
        })
        .catch(error => {
            next(error);
        })
    },
    delete_by_id(req, res, next) {
        req.person.getMailAddresses({where: {
            id: req.params.mail_address_id
        }})
        .then(([m]) => {
            if (!m) {
                throw {status: 404, message: "Pas trouvé 3"}
            }
            m.destroy();
            res.send("fait")
        })
        .catch(error => {
            next(error);
        })
    }
};