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

exports.getproduct = async (req, res) => {
  try {
    const products = await Product.find().sort({ createdAt: -1 });
    res.json(products);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

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

exports.addproduct = async (req, res) => {
  try {
    const { productCode, productName, quantitySold, unitPrice } = req.body;

    const existing = await Product.findOne({ productCode });
    if (existing) {
      return res.status(409).json({ message: 'Product code already exists' });
    }

    const newproduct = await Product.create({
      productCode,
      productName,
      quantitySold,
      unitPrice,
    });

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