const SparePart = require('../models/SparePart');

exports.getInventoryReport = async (req, res) => {
  try {
    const spareParts = await SparePart.find().populate('supplier');

    const totalSpareParts = spareParts.length;
    const totalStockValue = spareParts.reduce((sum, part) => {
      return sum + (part.unitPrice || 0) * (part.quantity || 0);
    }, 0);

    const lowStockParts = spareParts
      .filter((part) => part.quantity <= part.reorderLevel)
      .map((part) => ({
        id: part._id,
        partCode: part.partCode,
        partName: part.partName,
        quantity: part.quantity,
        reorderLevel: part.reorderLevel,
        supplier: part.supplier?.supplierName || 'N/A',
      }));

    res.json({
      totalSpareParts,
      totalStockValue,
      lowStockParts,
      spareParts,
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
