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

const createProduct = async (req, res) => {
  try {
    const existingProduct = await Product.findOne({ productCode: req.body.productCode });
    if (existingProduct) {
      return res.status(400).json({ message: "Product code already exists" });
    }

    const product = await Product.create(req.body);
    res.status(201).json({ message: "Product recorded successfully", product });
  } catch (error) {
    res.status(400).json({ message: "Product was not recorded", error: error.message });
  }
};

const getProducts = async (req, res) => {
  try {
    const products = await Product.find().sort({ createdAt: -1 });
    res.json(products);
  } catch (error) {
    res.status(500).json({ message: "Products could not be retrieved", error: error.message });
  }
};

module.exports = {
  createProduct,
  getProducts
};
