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


const flagCarAsSold = (req, res, next) =>
{
    carsModel.findByIdAndUpdate({_id: req.params.carID}, {sold: true})
    .then(data => next())
    .catch(err => next(err))
}


const createNewSaleDocument = (req, res, next) =>
{
    // Use the PayPal details to create a new sale document                
    let saleDetails = new Object()

    saleDetails.paypalPaymentID = req.params.orderID
    saleDetails.carID = req.params.carID
    saleDetails.price = req.params.price


    salesModel.create(saleDetails)
    .then(data => res.json({success:true}))
    .catch(err => next(err))
}


// Save a record of each Paypal payment
router.post('/sales/:orderID/:carID/:price', flagCarAsSold, createNewSaleDocument)


module.exports = router