var express = require('express');
var router = express.Router();
var product = require('../models/pcatalog');

router.get('/', function(req, res) {
	product.find(function (err, products) {
    	if (!err) {
      		return res.send(products);
    	} else {
      		return console.log(err);
    	}
  	});
});

router.post('/', function(req, res) {
	new product(req.body).save(function(err){
		if (!err) {
			return console.log("created product: " + req.body.sku);
		} else {
			return console.log(err);
		}
	});
	return res.send(req.body);
});

router.get('/:sku', function(req, res) {
	product.find({'sku': req.params.sku}, function(err, product){
		if (!err) {
			return res.send(product);
		} else {
			return res.send(err);
		}
	});
});

router.put('/:sku', function(req, res) {
	new product(req.body).update(function(err){
		if (!err) {
			return console.log("update product: " + req.body.sku);
		} else {
			return console.log(err);
		}
	});
	return res.send(req.body);
});

router.delete('/:sku', function(req, res) {
	product.remove({'sku': req.params.sku}, function(err) {
		if(!err) {
			console.log('deleted');
			return res.send('');
		} else {
			return console.log(err);
		}
	});
});

module.exports = router;