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

router.get('/', function(req, res) {
  Product.find().sort({ createdAt: -1 })
    .then(function(products) {
      res.json(products);
    })
    .catch(function(err) {
      res.status(400).json({ error: err.message });
    });
});

router.post('/', function(req, res) {
  var productCode = req.body.productCode;
  var productName = req.body.productName;
  var quantitySold = req.body.quantitySold;
  var unitPrice = req.body.unitPrice;

  if (!productCode || !productName || quantitySold == null || unitPrice == null) {
    return res.status(400).json({ message: 'All fields are required' });
  }

  Product.findOne({ productCode: productCode })
    .then(function(existing) {
      if (existing) {
        return res.status(400).json({ message: 'Product code already exists' });
      }
      var product = new Product(req.body);
      return product.save();
    })
    .then(function(product) {
      res.status(201).json(product);
    })
    .catch(function(err) {
      res.status(400).json({ error: err.message });
    });
});

module.exports = router;
