import SparePart from "../models/SparePartModel.js";
import StockOut from "../models/stockOutModel.js";

export const getStockStatus = async (req, res) => {
    try {
    const parts = await SparePart.find();

    const report = [];

    for (let part of parts) {
        const stockOuts = await StockOut.find({sparePart_id: part._id});


        const totalOut = stockOuts.reduce(
            (sum, item) => sum + item.stockOutQuantity,
            0
        );

        report.push({
            name: part.name,
            storedQuantity: part.quantity,
            stockOutQuantity: totalOut,
            remaining: part.quantity
        });
    }
    res.json(report);

} catch(err){
    res.status(500).json({message: err.message});
}
};

export const getDialyStockOut = async(req, res) =>{
    try{
        const today = new Date();

        const start = new Date(today.setHours(0, 0, 0, 0,));
        const end = new Date(today.setHours(23,59,59,999));

        const data = await StockOut.find({
            stockOutDate:{ $gte: start, $lte:end }
        }).populate("sparePart_id");

        res.json(data);
        
    } catch (err){
        res.status(500).json({message:err.message});
    }
};