const express = require('express');
const router = express.Router();
const Sales = require('../models/Sales');
const Product = require('../models/Product');
const StockStatus = require('../models/StockStatus');
const { requireAuth } = require('../middleware/auth');

// INSERT - Create sale
router.post('/', requireAuth, async (req, res) => {
  try {
    const { productId, soldQuantity, soldUnitPrice, salesDate } = req.body;

    const product = await Product.findById(productId);
    if (!product) return res.status(404).json({ message: 'Product not found' });

    // Check stock availability
    const stock = await StockStatus.findOne({ productId });
    if (!stock || stock.remainingQuantity < soldQuantity) {
      return res.status(400).json({
        message: `Insufficient stock. Available: ${stock ? stock.remainingQuantity : 0}`,
      });
    }

    const sale = new Sales({
      productId,
      soldQuantity,
      soldUnitPrice,
      salesDate: salesDate || new Date(),
    });
    await sale.save();

    // Update stock
    stock.soldQuantity += soldQuantity;
    stock.remainingQuantity = stock.availableQuantity - stock.soldQuantity;
    await stock.save();

    res.status(201).json({ message: 'Sale recorded successfully', sale });
  } catch (err) {
    res.status(500).json({ message: 'Error recording sale', error: err.message });
  }
});

// RETRIEVE - Get all sales
router.get('/', requireAuth, async (req, res) => {
  try {
    const sales = await Sales.find()
      .populate('productId', 'productName category')
      .sort({ salesDate: -1 });
    res.json(sales);
  } catch (err) {
    res.status(500).json({ message: 'Error fetching sales', error: err.message });
  }
});

// RETRIEVE - Get single sale
router.get('/:id', requireAuth, async (req, res) => {
  try {
    const sale = await Sales.findById(req.params.id).populate('productId', 'productName category');
    if (!sale) return res.status(404).json({ message: 'Sale not found' });
    res.json(sale);
  } catch (err) {
    res.status(500).json({ message: 'Error fetching sale', error: err.message });
  }
});

// UPDATE - Update sale
router.put('/:id', requireAuth, async (req, res) => {
  try {
    const { soldQuantity, soldUnitPrice, salesDate } = req.body;
    const soldTotalPrice = soldQuantity * soldUnitPrice;

    const oldSale = await Sales.findById(req.params.id);
    if (!oldSale) return res.status(404).json({ message: 'Sale not found' });

    const quantityDiff = soldQuantity - oldSale.soldQuantity;

    // Check stock if increasing quantity
    if (quantityDiff > 0) {
      const stock = await StockStatus.findOne({ productId: oldSale.productId });
      if (!stock || stock.remainingQuantity < quantityDiff) {
        return res.status(400).json({ message: 'Insufficient stock for update' });
      }
    }

    const sale = await Sales.findByIdAndUpdate(
      req.params.id,
      { soldQuantity, soldUnitPrice, soldTotalPrice, salesDate, updatedAt: new Date() },
      { new: true }
    );

    // Update stock
    const stock = await StockStatus.findOne({ productId: oldSale.productId });
    if (stock) {
      stock.soldQuantity += quantityDiff;
      stock.remainingQuantity = stock.availableQuantity - stock.soldQuantity;
      await stock.save();
    }

    res.json({ message: 'Sale updated successfully', sale });
  } catch (err) {
    res.status(500).json({ message: 'Error updating sale', error: err.message });
  }
});

// DELETE - Delete sale
router.delete('/:id', requireAuth, async (req, res) => {
  try {
    const sale = await Sales.findByIdAndDelete(req.params.id);
    if (!sale) return res.status(404).json({ message: 'Sale not found' });

    // Restore stock
    const stock = await StockStatus.findOne({ productId: sale.productId });
    if (stock) {
      stock.soldQuantity -= sale.soldQuantity;
      stock.remainingQuantity = stock.availableQuantity - stock.soldQuantity;
      await stock.save();
    }

    res.json({ message: 'Sale deleted successfully' });
  } catch (err) {
    res.status(500).json({ message: 'Error deleting sale', error: err.message });
  }
});

module.exports = router;
