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

// ✅ CREATE
export const createStockOut = async (req, res) => {
  try {
    const { sparePart_id, stockOutQuantity, stockOutUnitPrice } = req.body;

    if (!sparePart_id || !stockOutQuantity || !stockOutUnitPrice) {
      return res.status(400).json({ message: "All fields are required" });
    }

    const part = await SparePart.findById(sparePart_id);

    if (!part) {
      return res.status(404).json({ message: "Spare part not found" });
    }

    if (part.quantity < stockOutQuantity) {
      return res.status(400).json({ message: "Insufficient stock" });
    }

    const total = stockOutQuantity * stockOutUnitPrice;

    const stockOut = await StockOut.create({
      sparePart_id,
      stockOutQuantity,
      stockOutUnitPrice,
      stockOutTotalPrice: total
    });

    // decrease stock
    await SparePart.findByIdAndUpdate(sparePart_id, {
      $inc: { quantity: -stockOutQuantity }
    });
    
    await SparePart.findByIdAndUpdate(sparePart_id, {
    totalPrice: part.quantity * part.unitPrice
    });

    res.status(201).json(stockOut);

  } catch (error) {
    console.log("CREATE ERROR:", error.message);
    res.status(500).json({ message: error.message });
  }
};



// ✅ GET ALL
export const getStockOuts = async (req, res) => {
  try {
    const data = await StockOut.find().populate("sparePart_id");
    res.json(data);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};



// ✅ UPDATE
export const updateStockOut = async (req, res) => {
  try {
    const { id } = req.params;
    const { stockOutQuantity, stockOutUnitPrice } = req.body;

    const stockOut = await StockOut.findById(id);

    if (!stockOut) {
      return res.status(404).json({ message: "StockOut not found" });
    }

    const newTotal = stockOutQuantity * stockOutUnitPrice;

    stockOut.stockOutQuantity = stockOutQuantity;
    stockOut.stockOutUnitPrice = stockOutUnitPrice;
    stockOut.stockOutTotalPrice = newTotal;

    await stockOut.save();

    res.json(stockOut);

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



// ✅ DELETE
export const deleteStockOut = async (req, res) => {
  try {
    const { id } = req.params;

    const stockOut = await StockOut.findById(id);

    if (!stockOut) {
      return res.status(404).json({ message: "StockOut not found" });
    }

    await stockOut.deleteOne();

    res.json({ message: "Deleted successfully" });

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