const router = require(`express`).Router()
const createError = require('http-errors')
const carsModel = require(`../models/cars`)


// read all records
router.get(`/cars`, (req, res, next) => 
{   
    //user does not have to be logged in to see car details
    carsModel.find({})
    .then(data => res.json(data))
    .catch(err => next(err))
})


// Read one record
router.get(`/cars/:id`, (req, res, next) => 
{
    carsModel.findById(req.params.id)
    .then(data => res.json(data))
    .catch(err => next(err))
})


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


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


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

module.exports = router