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

var populateSale = function(query) {
  return query.populate('customer', 'firstName lastName customerNumber');
};

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

router.get('/:id', function(req, res) {
  populateSale(Sale.findById(req.params.id))
    .then(function(sale) {
      if (!sale) return res.status(404).json({ error: 'Sale not found' });
      res.json(sale);
    })
    .catch(function(err) {
      res.status(400).json({ error: err.message });
    });
});

router.post('/', function(req, res) {
  var invoiceNumber = req.body.invoiceNumber;
  var salesDate = req.body.salesDate;
  var paymentMethod = req.body.paymentMethod;
  var totalAmountPaid = req.body.totalAmountPaid;
  var customer = req.body.customer;
  var products = req.body.products || [];

  if (!invoiceNumber || !salesDate || !paymentMethod || totalAmountPaid == null || !customer) {
    return res.status(400).json({ message: 'All fields are required' });
  }

  Sale.findOne({ invoiceNumber: invoiceNumber })
    .then(function(existing) {
      if (existing) {
        return res.status(400).json({ message: 'Invoice number already exists' });
      }
      var sale = new Sale({
        invoiceNumber: invoiceNumber,
        salesDate: salesDate,
        paymentMethod: paymentMethod,
        totalAmountPaid: totalAmountPaid,
        customer: customer,
        products: products
      });
      return sale.save();
    })
    .then(function(sale) {
      return sale.populate('customer', 'firstName lastName customerNumber');
    })
    .then(function(sale) {
      res.status(201).json(sale);
    })
    .catch(function(err) {
      res.status(400).json({ error: err.message });
    });
});

router.put('/:id', function(req, res) {
  var invoiceNumber = req.body.invoiceNumber;

  var checkInvoice = function() {
    if (!invoiceNumber) return Promise.resolve();
    return Sale.findOne({ invoiceNumber: invoiceNumber, _id: { $ne: req.params.id } })
      .then(function(existing) {
        if (existing) {
          return Promise.reject({ status: 400, message: 'Invoice number already exists' });
        }
      });
  };

  checkInvoice()
    .then(function() {
      return populateSale(
        Sale.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true })
      );
    })
    .then(function(sale) {
      if (!sale) return res.status(404).json({ error: 'Sale not found' });
      res.json(sale);
    })
    .catch(function(err) {
      if (err.status) return res.status(err.status).json({ message: err.message });
      res.status(400).json({ error: err.message });
    });
});

router.delete('/:id', function(req, res) {
  Sale.findByIdAndDelete(req.params.id)
    .then(function() {
      res.json({ message: 'Sale deleted' });
    })
    .catch(function(err) {
      res.status(400).json({ error: err.message });
    });
});

module.exports = router;
