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

exports.getSpareParts = async (req, res) => {
  try {
    const parts = await SparePart.find().populate('supplier');
    res.json(parts);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.getSparePartById = async (req, res) => {
  try {
    const part = await SparePart.findById(req.params.id).populate('supplier');
    if (!part) {
      return res.status(404).json({ message: 'Spare part not found' });
    }
    res.json(part);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.addSparePart = async (req, res) => {
  try {
    const { partCode, partName, category, unitPrice, quantity, reorderLevel, supplier } = req.body;
    const newPart = await SparePart.create({
      partCode,
      partName,
      category,
      unitPrice: Number(unitPrice),
      quantity: Number(quantity),
      reorderLevel: Number(reorderLevel || 5),
      supplier,
      createdBy: req.user._id,
    });

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

exports.updateSparePart = async (req, res) => {
  try {
    const updatedPart = await SparePart.findByIdAndUpdate(
      req.params.id,
      {
        partCode: req.body.partCode,
        partName: req.body.partName,
        category: req.body.category,
        unitPrice: Number(req.body.unitPrice),
        quantity: Number(req.body.quantity),
        reorderLevel: Number(req.body.reorderLevel),
        supplier: req.body.supplier,
      },
      { new: true }
    );

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

    res.json({ message: 'Spare part updated successfully', data: updatedPart });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.deleteSparePart = async (req, res) => {
  try {
    const deletedPart = await SparePart.findByIdAndDelete(req.params.id);
    if (!deletedPart) {
      return res.status(404).json({ message: 'Spare part not found' });
    }

    res.json({ message: 'Spare part deleted successfully' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
