const router = require(`express`).Router()

const carsModel = require(`../models/cars`)


// read all records
router.get(`/cars`, (req, res, next) => 
{     
    carsModel.get()
    .then(collection => 
    {
        let data = collection.docs.map(doc => 
        {
            // As the firestore document.data does not contain the document's id, we need to combine document data and document id
            let docDataAndId = doc.data()
            docDataAndId._id = doc.id
            return docDataAndId
        })
        
        res.json(data)
    })
    .catch(err => next(err))
})


// Read one record
router.get(`/cars/:id`, (req, res, next) => 
{
    carsModel.doc(req.params.id).get()
    .then(doc =>
    {
        // As the firestore document.data does not contain the document's id, we need to combine document data and document id
        let docDataAndId = doc.data()
        docDataAndId._id = doc.id
        
        res.json(docDataAndId)
    })
    .catch(err => next(err))
})


// Add new record
router.post(`/cars`, (req, res, next) => 
{
    carsModel.add(req.body)
    .then(() => 
    {
        res.json(req.body)
    })
    .catch(err => next(err))
})


// Update one record
router.put(`/cars/:id`, (req, res, next) => 
{
    carsModel.doc(req.params.id).update(req.body)    
    .then(() => 
    {
        res.json(req.body)
    })
    .catch(err => next(err))
})


// Delete one record
router.delete(`/cars/:id`, (req, res, next) => 
{
    carsModel.doc(req.params.id).delete()
    .then(() => 
    {
        res.json(req.body)   
    })
    .catch(err => next(err))
})

module.exports = router