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

router.post('/', async (req, res) => {
  try {
    const { invoiceNumber, salesDate, paymentMethod, totalAmountPaid, customerNumber, productCode, quantitySold } = req.body;
    const sale = await Sale.create({ invoiceNumber, salesDate, paymentMethod, totalAmountPaid, customerNumber, productCode, quantitySold });
    await Product.findOneAndUpdate({ productCode }, { $inc: { quantitySold: Number(quantitySold) } });
    res.status(201).json(sale);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

router.get('/', async (req, res) => {
  try {
    const sales = await Sale.find().sort({ salesDate: -1 });
    res.json(sales);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const sale = await Sale.findById(req.params.id);
    if (!sale) return res.status(404).json({ message: 'Sale not found' });
    res.json(sale);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

router.put('/:id', async (req, res) => {
  try {
    const update = req.body;
    const sale = await Sale.findById(req.params.id);
    if (!sale) return res.status(404).json({ message: 'Sale not found' });

    if (update.quantitySold && update.productCode && (update.productCode === sale.productCode)) {
      const quantityChange = Number(update.quantitySold) - Number(sale.quantitySold);
      await Product.findOneAndUpdate({ productCode: sale.productCode }, { $inc: { quantitySold: quantityChange } });
    }

    const updatedSale = await Sale.findByIdAndUpdate(req.params.id, update, { new: true });
    res.json(updatedSale);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

router.delete('/:id', async (req, res) => {
  try {
    const sale = await Sale.findById(req.params.id);
    if (!sale) return res.status(404).json({ message: 'Sale not found' });
    await Product.findOneAndUpdate({ productCode: sale.productCode }, { $inc: { quantitySold: -Number(sale.quantitySold) } });
    await sale.deleteOne();
    res.json({ message: 'Sale deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router;
