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

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

router.post('/', function(req, res) {
  var customerNumber = req.body.customerNumber;
  var firstName = req.body.firstName;
  var lastName = req.body.lastName;
  var telephone = req.body.telephone;
  var address = req.body.address;

  if (!customerNumber || !firstName || !lastName || !telephone || !address) {
    return res.status(400).json({ message: 'All fields are required' });
  }

  Customer.findOne({ customerNumber: customerNumber })
    .then(function(existing) {
      if (existing) {
        return res.status(400).json({ message: 'Customer number already exists' });
      }
      var customer = new Customer(req.body);
      return customer.save();
    })
    .then(function(customer) {
      res.status(201).json(customer);
    })
    .catch(function(err) {
      res.status(400).json({ error: err.message });
    });
});

module.exports = router;
