var Auto = require('../models/auto.js');

function list_autos(req, res) {
    Auto.find({}, (err, auto) => {
        if (err) {
            return res.status(500).send({ message: 'Error: Could not get autos!' });
        }
        res.status(200).send({ auto });
    }).populate('marca')
}

function new_auto(req, res) {
    try{
        let auto = new Auto();
        auto.patente = req.body.patente;
        auto.anio = req.body.anio;
        auto.marca = req.body.marca;
        auto.save((err, autoSave) => {
            if (err) {
                return res.status(400).send({ message: `Error: Could not save auto to database!> ${err}` });
            }
            res.status(200).send({ auto: autoSave });
        })
    } 
    catch (error) {
        res.status(500).send({ message: `error: ` + error });
    }
}

function delete_auto(req, res) {
    let id = { '_id': req.params.id };
    Auto.deleteOne(id, (err, auto) => {
        if (err) {
            return res.status(400).send({ message: `Error: Could not delete auto from database!> ${err}` });
        }
        if (auto.deletedCount == 1) {
            res.status(200).send({ message: `Auto deleted!` });
        }
        else {
            res.status(400).send({ message: `Error: Auto could not be deleted!` });
        }
    });
}

module.exports = {
    list_autos,
    new_auto,
    delete_auto
};
