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

const router = express.Router();
router.use(authMiddleware);

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

router.get('/:id', async (req, res) => {
  try {
    const [products] = await pool.query('SELECT * FROM products WHERE product_id = ?', [req.params.id]);
    if (products.length === 0) {
      return res.status(404).json({ message: 'Product not found.' });
    }
    res.json(products[0]);
  } catch (error) {
    console.error('Get product error:', error);
    res.status(500).json({ message: 'Failed to fetch product.' });
  }
});

router.post('/', async (req, res) => {
  try {
    const { product_name, category, quantity, price } = req.body;
    if (!product_name || !category || quantity === undefined || !price) {
      return res.status(400).json({ message: 'All product fields are required.' });
    }

    const [result] = await pool.query(
      'INSERT INTO products (product_name, category, quantity, price) VALUES (?, ?, ?, ?)',
      [product_name, category, quantity, price]
    );

    const [newProduct] = await pool.query('SELECT * FROM products WHERE product_id = ?', [result.insertId]);
    res.status(201).json(newProduct[0]);
  } catch (error) {
    console.error('Create product error:', error);
    res.status(500).json({ message: 'Failed to create product.' });
  }
});

router.put('/:id', async (req, res) => {
  try {
    const { product_name, category, quantity, price } = req.body;
    const [existing] = await pool.query('SELECT * FROM products WHERE product_id = ?', [req.params.id]);
    if (existing.length === 0) {
      return res.status(404).json({ message: 'Product not found.' });
    }

    await pool.query(
      'UPDATE products SET product_name = ?, category = ?, quantity = ?, price = ? WHERE product_id = ?',
      [product_name, category, quantity, price, req.params.id]
    );

    const [updated] = await pool.query('SELECT * FROM products WHERE product_id = ?', [req.params.id]);
    res.json(updated[0]);
  } catch (error) {
    console.error('Update product error:', error);
    res.status(500).json({ message: 'Failed to update product.' });
  }
});

router.delete('/:id', async (req, res) => {
  try {
    const [existing] = await pool.query('SELECT * FROM products WHERE product_id = ?', [req.params.id]);
    if (existing.length === 0) {
      return res.status(404).json({ message: 'Product not found.' });
    }

    const [sales] = await pool.query('SELECT * FROM sales WHERE product_id = ?', [req.params.id]);
    if (sales.length > 0) {
      return res.status(400).json({ message: 'Cannot delete product with existing sales records.' });
    }

    await pool.query('DELETE FROM products WHERE product_id = ?', [req.params.id]);
    res.json({ message: 'Product deleted successfully.' });
  } catch (error) {
    console.error('Delete product error:', error);
    res.status(500).json({ message: 'Failed to delete product.' });
  }
});

module.exports = router;
