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

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

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

    const product = new Product({
      productCode,
      productName,
      category,
      quantityInStock,
      unitPrice,
      supplierName,
      dateReceived,
    });

    await product.save();
    res.status(201).json({ message: 'Product created successfully', product });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

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

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

    const product = await Product.findById(req.params.id);
    if (!product) {
      return res.status(404).json({ message: 'Product not found' });
    }

    // If productCode is changing, ensure uniqueness
    if (productCode && productCode !== product.productCode) {
      const existingProduct = await Product.findOne({ productCode });
      if (existingProduct) {
        return res.status(400).json({ message: 'Product code already exists' });
      }
    }

    product.productCode = productCode ?? product.productCode;
    product.productName = productName ?? product.productName;
    product.category = category ?? product.category;
    product.quantityInStock = quantityInStock ?? product.quantityInStock;
    product.unitPrice = unitPrice ?? product.unitPrice;
    product.supplierName = supplierName ?? product.supplierName;
    product.dateReceived = dateReceived ?? product.dateReceived;

    await product.save();

    res.status(200).json({ message: 'Product updated successfully', product });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

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

    await Product.findByIdAndDelete(req.params.id);
    res.status(200).json({ message: 'Product deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

