const express = require('express');
const pool = require('../config/db');
const authMiddleware = require('../middleware/auth');

const router = express.Router();

router.get('/', authMiddleware, async (req, res) => {
  try {
    const [products] = await pool.query('SELECT * FROM Product ORDER BY productCode');
    res.json(products);
  } catch (error) {
    res.status(500).json({ message: 'Failed to fetch products.', error: error.message });
  }
});

router.post('/', authMiddleware, async (req, res) => {
  try {
    const { productCode, productName, category, quantityInStock, unitPrice, supplierName, dateReceived } = req.body;

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

    await pool.query(
      `INSERT INTO Product (productCode, productName, category, quantityInStock, unitPrice, supplierName, dateReceived)
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [productCode, productName, category, quantityInStock, unitPrice, supplierName, dateReceived]
    );

    res.status(201).json({ message: 'Product added successfully.' });
  } catch (error) {
    if (error.code === 'ER_DUP_ENTRY') {
      return res.status(409).json({ message: 'Product code already exists.' });
    }
    res.status(500).json({ message: 'Failed to add product.', error: error.message });
  }
});

module.exports = router;
