const { getCollections, getNextSequence } = require('../config/db');


// Get all products
const getProducts = async (req, res) => {
  try {
    const { products } = await getCollections();
    const rows = await products
      .find({})
      .sort({ created_date: -1 })
      .toArray();
    res.json(rows);
  } catch (err) {
    res.status(500).json({ message: 'Server error.' });
  }
};

// Get single product
const getProduct = async (req, res) => {
  try {
    const { products } = await getCollections();
    const row = await products.findOne({ product_id: Number(req.params.id) });
    if (!row) return res.status(404).json({ message: 'Product not found.' });
    res.json(row);
  } catch (err) {
    res.status(500).json({ message: 'Server error.' });
  }
};

// Add product
const addProduct = async (req, res) => {
  const { product_name, category, price, stock } = req.body;
  if (!product_name || !category || price === undefined)
    return res.status(400).json({ message: 'Product name, category and price are required.' });

  try {
    const { products } = await getCollections();

    const product_id = await getNextSequence('products');
    await products.insertOne({
      product_id,
      product_name,
      category,
      price,
      stock: stock ?? 0,
      created_date: new Date()
    });

    res.status(201).json({ message: 'Product added.', product_id });
  } catch (err) {
    res.status(500).json({ message: 'Server error.' });
  }
};

// Update product
const updateProduct = async (req, res) => {
  const { product_name, category, price, stock } = req.body;
  try {
    const { products } = await getCollections();
    const result = await products.updateOne(
      { product_id: Number(req.params.id) },
      { $set: { product_name, category, price, stock } }
    );

    if (result.matchedCount === 0) return res.status(404).json({ message: 'Product not found.' });
    res.json({ message: 'Product updated.' });
  } catch (err) {
    res.status(500).json({ message: 'Server error.' });
  }
};

// Delete product
const deleteProduct = async (req, res) => {
  try {
    const { products } = await getCollections();
    const result = await products.deleteOne({ product_id: Number(req.params.id) });
    if (result.deletedCount === 0) return res.status(404).json({ message: 'Product not found.' });
    res.json({ message: 'Product deleted.' });
  } catch (err) {
    res.status(500).json({ message: 'Server error.' });
  }
};

module.exports = { getProducts, getProduct, addProduct, updateProduct, deleteProduct };

