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


exports.getproduct = async (req, res) => {
  try {
    const products = await Product.find().populate('Supplier');
    if (!products) {
      return res.status(404).json({ message: 'Products not found' });
    }
    res.json(products);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
}

exports.getproductbyid = async (req, res) => {
  try {
    const productById = await Product.findById(req.params.id).populate('Supplier');
    if (!productById) {
      return res.status(404).json({ message: 'Product not found' });
    }
    res.json(productById);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.addproduct = async (req, res) => {
  try {
    const { productCode, productName, category, unitPrice, quantity, expiryDate } = req.body
    const newproduct = await Product.create({
      productCode,
      productName,
      category,
      unitPrice,
      quantity,
      expiryDate,
      Supplier: req.user._id
    });

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

exports.updateproduct = async (req, res) => {
  try {
    const updateproducts = await Product.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    );
    if (!updateproducts) return res.status(404).json({ msg: " product not found" })

    res.json({ msg: "Products updated Syccessfully", data: updateproducts });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
}

exports.deleteproduct = async (req, res) => {
  try {
    const deleteproduct = await Product.findByIdAndDelete(
      req.params.id
    );
    if (!deleteproduct) {
      return res.status(404).json({ message: 'product not found' });
    }
    res.json({ message: 'Product deleted successfully' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
}
