const supplier = require('../models/Supplier');

exports.addsupplier = async (req, res) => {
  try {
    const newsupplier = new supplier(req.body);
    await newsupplier.save();
    res.status(200).json({ msg: 'Supplier added successful' });
  } catch (error) {
    res.status(500).json({ msg: 'Failed to add supplier', error: error.message });
  }
};

exports.getsupplierbyid = async (req, res) => {
  try {
    const singlesupplier = await supplier.findById(req.params.id);

    if (!singlesupplier) return res.status(404).json({ msg: 'Supplier not found' });

    res.status(200).json(singlesupplier);
  } catch (error) {
    res.status(500).json({ msg: 'failed to fetch', error: error.message });
  }
};

exports.getsupplier = async (req, res) => {
  try {
    const getsupplier = await supplier.find();
    res.status(200).json(getsupplier);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

exports.updatesupplier = async (req, res) => {
  try {
    const updatesupplier = await supplier.findByIdAndUpdate(req.params.id, req.body, {
      new: true,
    });

    if (!updatesupplier) return res.status(404).json({ msg: 'Supplier not found' });

    res.status(200).json({ msg: 'updated successfully' });
  } catch (error) {
    res.status(500).json({ msg: 'Failed to update', error: error.message });
  }
};

exports.deletesupplier = async (req, res) => {
  try {
    const deletesupplier = await supplier.findByIdAndDelete(req.params.id);

    if (!deletesupplier) return res.status(404).json({ msg: 'Supplier not found' });

    res.status(200).json({ msg: 'Deleted successfully' });
  } catch (error) {
    res.status(500).json({ msg: 'Failed to delete', error: error.message });
  }
};