const { getCollections, getNextSequence } = require('../config/db');

// Get all sales
const getSales = async (req, res) => {
  try {
    const { sales } = await getCollections();
    const rows = await sales.find({}).sort({ sale_date: -1 }).toArray();
    res.json(rows);
  } catch (err) {
    res.status(500).json({ message: 'Server error.' });
  }
};

// Record a sale
const recordSale = async (req, res) => {
  const { customer_id, product_id, quantity } = req.body;
  if (!customer_id || !product_id || !quantity)
    return res.status(400).json({ message: 'Customer, product and quantity are required.' });

  try {
    const { customers, products, sales } = await getCollections();

    const cust = await customers.findOne({ customer_id: Number(customer_id) });
    if (!cust) return res.status(404).json({ message: 'Customer not found.' });

    const product = await products.findOne({ product_id: Number(product_id) });
    if (!product) return res.status(404).json({ message: 'Product not found.' });

    const qtyNum = Number(quantity);
    if (product.stock < qtyNum)
      return res.status(400).json({ message: `Insufficient stock. Available: ${product.stock}` });

    const unit_price = product.price;
    const total_price = unit_price * qtyNum;

    // decrement stock atomically
    const stockRes = await products.updateOne(
      { product_id: Number(product_id), stock: { $gte: qtyNum } },
      { $inc: { stock: -qtyNum } }
    );

    if (stockRes.matchedCount === 0) {
      // stock changed between reads
      return res.status(400).json({ message: `Insufficient stock. Available: ${product.stock}` });
    }

    const sale_id = await getNextSequence('sales');

    await sales.insertOne({
      sale_id,
      customer_id: Number(customer_id),
      customer_name: cust.full_name,
      product_id: Number(product_id),
      product_name: product.product_name,
      quantity: qtyNum,
      unit_price,
      total_price,
      sale_date: new Date()
    });

    res.status(201).json({ message: 'Sale recorded successfully.', total_price });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Server error.' });
  }
};

// Delete sale
const deleteSale = async (req, res) => {
  try {
    const { sales, products } = await getCollections();

    const sale = await sales.findOne({ sale_id: Number(req.params.id) });
    if (!sale) return res.status(404).json({ message: 'Sale not found.' });

    // Restore stock
    await products.updateOne(
      { product_id: sale.product_id },
      { $inc: { stock: sale.quantity } }
    );

    await sales.deleteOne({ sale_id: Number(req.params.id) });

    res.json({ message: 'Sale deleted and stock restored.' });
  } catch (err) {
    res.status(500).json({ message: 'Server error.' });
  }
};

module.exports = { getSales, recordSale, deleteSale };

