import StockIn from "../models/stockInModel.js";
import SparePart from "../models/SparePartModel.js";

export const createStockIn = async (req, res) =>{
    try {
        const {  SparePart_id, StockInQuantity} = req.body;

        if( !SparePart_id || !StockInQuantity){
            return res.status(400).json({message:"Please fill out all fields"});
        }

        const stockIn = await StockIn.create({
            SparePart_id,
            StockInQuantity
        });

        await SparePart.findByIdAndUpdate(SparePart_id,{
            $inc:{ quantity: StockInQuantity}
        });

        const part = await SparePart.findById(SparePart_id);

        await SparePart.findByIdAndUpdate(SparePart_id, {
        totalPrice: part.quantity * part.unitPrice
        });


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