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

// GET all stock statuses
router.get('/', requireAuth, async (req, res) => {
  try {
    const stocks = await StockStatus.find()
      .populate('productId', 'productName category unitPrice')
      .sort({ updatedAt: -1 });
    res.json(stocks);
  } catch (err) {
    res.status(500).json({ message: 'Error fetching stock', error: err.message });
  }
});

// GET single stock
router.get('/:id', requireAuth, async (req, res) => {
  try {
    const stock = await StockStatus.findById(req.params.id)
      .populate('productId', 'productName category unitPrice');
    if (!stock) return res.status(404).json({ message: 'Stock record not found' });
    res.json(stock);
  } catch (err) {
    res.status(500).json({ message: 'Error fetching stock', error: err.message });
  }
});

// UPDATE stock
router.put('/:id', requireAuth, async (req, res) => {
  try {
    const { availableQuantity } = req.body;
    const stock = await StockStatus.findById(req.params.id);
    if (!stock) return res.status(404).json({ message: 'Stock record not found' });

    stock.availableQuantity = availableQuantity;
    stock.remainingQuantity = availableQuantity - stock.soldQuantity;
    stock.updatedAt = new Date();
    await stock.save();

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

// DELETE stock record
router.delete('/:id', requireAuth, async (req, res) => {
  try {
    const stock = await StockStatus.findByIdAndDelete(req.params.id);
    if (!stock) return res.status(404).json({ message: 'Stock record not found' });
    res.json({ message: 'Stock record deleted successfully' });
  } catch (err) {
    res.status(500).json({ message: 'Error deleting stock record', error: err.message });
  }
});

module.exports = router;
