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

exports.addStockIn = async (req, res) => {
  try {
    const { date, quantity, unitCost, notes, sparePart } = req.body;
    const part = await SparePart.findById(sparePart);

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

    const newStockIn = await StockIn.create({
      date: new Date(date),
      quantity: Number(quantity),
      unitCost: Number(unitCost),
      notes,
      sparePart,
      createdBy: req.user._id,
    });

    part.quantity += Number(quantity);
    await part.save();

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

exports.getStockIns = async (req, res) => {
  try {
    const records = await StockIn.find().populate('sparePart');
    res.json(records);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.addStockOut = async (req, res) => {
  try {
    const { date, quantity, reason, destination, sparePart } = req.body;
    const part = await SparePart.findById(sparePart);

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

    const requestedQuantity = Number(quantity);
    if (part.quantity < requestedQuantity) {
      return res.status(400).json({ message: 'Not enough quantity in stock' });
    }

    const newStockOut = await StockOut.create({
      date: new Date(date),
      quantity: requestedQuantity,
      reason,
      destination,
      sparePart,
      createdBy: req.user._id,
    });

    part.quantity -= requestedQuantity;
    await part.save();

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

exports.getStockOuts = async (req, res) => {
  try {
    const records = await StockOut.find().populate('sparePart');
    res.json(records);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
