const express = require('express');
const router = express.Router();
const Product = require('../models/Product');
const StockStatus = require('../models/StockStatus');
const { requireAuth } = require('../middleware/auth');

// INSERT - Create product
router.post('/', requireAuth, async (req, res) => {
  try {
    const { productName, category, quantity, unitPrice } = req.body;
    const product = new Product({ productName, category, quantity, unitPrice });
    await product.save();

    // Create initial stock status
    const stock = new StockStatus({
      productId: product._id,
      availableQuantity: quantity,
      soldQuantity: 0,
      remainingQuantity: quantity,
    });
    await stock.save();

    res.status(201).json({ message: 'Product added successfully', product });
  } catch (err) {
    res.status(500).json({ message: 'Error adding product', error: err.message });
  }
});

// RETRIEVE - Get all products
router.get('/', requireAuth, async (req, res) => {
  try {
    const products = await Product.find().sort({ createdAt: -1 });
    res.json(products);
  } catch (err) {
    res.status(500).json({ message: 'Error fetching products', error: err.message });
  }
});

// RETRIEVE - Get single product
router.get('/:id', requireAuth, 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 (err) {
    res.status(500).json({ message: 'Error fetching product', error: err.message });
  }
});

// UPDATE - Update product (only last form)
router.put('/:id', requireAuth, async (req, res) => {
  try {
    const { productName, category, quantity, unitPrice } = req.body;
    const totalPrice = quantity * unitPrice;

    const product = await Product.findByIdAndUpdate(
      req.params.id,
      { productName, category, quantity, unitPrice, totalPrice, updatedAt: new Date() },
      { new: true, runValidators: true }
    );

    if (!product) return res.status(404).json({ message: 'Product not found' });

    // Update stock status
    await StockStatus.findOneAndUpdate(
      { productId: req.params.id },
      { availableQuantity: quantity, updatedAt: new Date() }
    );

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

// DELETE - Delete product (only last form)
router.delete('/:id', requireAuth, async (req, res) => {
  try {
    const product = await Product.findByIdAndDelete(req.params.id);
    if (!product) return res.status(404).json({ message: 'Product not found' });

    await StockStatus.findOneAndDelete({ productId: req.params.id });

    res.json({ message: 'Product deleted successfully' });
  } catch (err) {
    res.status(500).json({ message: 'Error deleting product', error: err.message });
  }
});

module.exports = router;
