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) => 
{
    // validate input
    const today = new Date();
    if(!/^[a-zA-Z]+$/.test(req.body.model))
    {
        next(createError(400, `Model must be a string`))
    }
    else if(!/^[a-zA-Z]+$/.test(req.body.colour))
    {
        next(createError(400, `Colour must be a string`))      
    }
    else if(req.body.year < 1990)     // between 1990 and the current year
    {
        next(createError(400, `Year needs to be greater than or equal to 1990`))      
    }
    else if(req.body.year > today.getFullYear())
    {
        next(createError(400, `Year needs to be this year or less`))      
    }
    else if(req.body.price < 1000 || req.body.price > 100000)       // between €1000 and €100000                
    {
        next(createError(400, `Price needs to be between €1000 and €100000`))
    }
    else // input is valid
    {    
        carsModel.create(req.body)
        .then(data => 
        {
            res.json(data)
        })
        .catch(err => next(err))
    }
})


// Update one record
router.put(`/cars/:id`, (req, res, next) => 
{
    // validate input
    const today = new Date();
    if(!/^[a-zA-Z]+$/.test(req.body.model))
    {
        next(createError(400, `Model must be a string`))
    }
    else if(!/^[a-zA-Z]+$/.test(req.body.colour))
    {
        next(createError(400, `Colour must be a string`))       
    }
    else if(req.body.year < 1990)     // between 1990 and the current year
    {
        next(createError(400, `Year needs to be greater than or equal to 1990`))        
    }
    else if(req.body.year > today.getFullYear())
    {
        next(createError(400, `Year needs to be this year or less`))       
    }
    else if(req.body.price < 1000 || req.body.price > 100000)       // between €1000 and €100000                
    {
        next(createError(400, `Price needs to be between €1000 and €100000`)) 
    }
    else // input is valid
    {
        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