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