import Product from '../models/Product.js';

const createProduct = async (req, res) => {
  try {
    const { productCode, productName, category, quantityInStock, unitPrice, supplierName, dateReceived } = req.body;

    if (!productCode || !productName || !category || unitPrice === undefined || !supplierName || !dateReceived) {
      return res.status(400).json({ message: 'All fields are required' });
    }

    const productExists = await Product.findOne({ productCode });

    if (productExists) {
      return res.status(400).json({ message: 'Product code already exists' });
    }

    const product = await Product.create({
      productCode,
      productName,
      category,
      quantityInStock: quantityInStock || 0,
      unitPrice,
      supplierName,
      dateReceived,
    });

    res.status(201).json(product);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

const getAllProducts = async (req, res) => {
  try {
    const products = await Product.find({});
    res.json(products);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

const getSingleProduct = 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 (error) {
    res.status(500).json({ message: error.message });
  }
};

export { createProduct, getAllProducts, getSingleProduct };
