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

const jwt = require('jsonwebtoken')

// 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))
})


// Read one record
router.get(`/cars/:id`, (req, res, next) => 
{
    jwt.verify(req.headers.authorization, process.env.JWT_PRIVATE_KEY, {algorithm: "HS256"}, (err, decodedToken) => 
    {
        if (err) 
        { 
            next(createError(403, `User is not logged in`))
        }
        else
        {
            carsModel.findById(req.params.id)
            .then(data => res.json(data))
            .catch(err => next(err))
        }
    })
})


// Add new record
router.post(`/cars`, (req, res, next) => 
{
    jwt.verify(req.headers.authorization, process.env.JWT_PRIVATE_KEY, {algorithm: "HS256"}, (err, decodedToken) => 
    {
        if (err) 
        { 
            next(createError(403, `User is not logged in`))
        }
        else
        {
            if(decodedToken.accessLevel >= process.env.ACCESS_LEVEL_ADMIN)
            {                
                // Use the new car details to create a new car document
                carsModel.create(req.body)
                .then(data => res.json(data))
                .catch(err => next(createError(500, `User is not an administrator, so they cannot add new records`)))
            }
        }
    })
})


// Update one record
router.put(`/cars/:id`, (req, res, next) => 
{
    jwt.verify(req.headers.authorization, process.env.JWT_PRIVATE_KEY, {algorithm: "HS256"}, (err, decodedToken) => 
    {
        if (err) 
        { 
            next(createError(403, `User is not logged in`))
        }
        else
        {
            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) => 
{
    jwt.verify(req.headers.authorization, process.env.JWT_PRIVATE_KEY, {algorithm: "HS256"}, (err, decodedToken) => 
    {
        if (err) 
        { 
            next(createError(403, `User is not logged in`))
        }
        else
        {
            if(decodedToken.accessLevel >= process.env.ACCESS_LEVEL_ADMIN)
            {
                carsModel.findByIdAndDelete(req.params.id)
                .then(data => res.json(data))
                .catch(err => next(err))
            }
            else
            {
                next(createError(500, `User is not an administrator, so they cannot delete records`))
            }        
        }
    })
})

module.exports = router