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

// Daily Sales Report
router.get('/daily-sales', requireAuth, async (req, res) => {
  try {
    const { date } = req.query;
    const targetDate = date ? new Date(date) : new Date();
    const startOfDay = new Date(targetDate.setHours(0, 0, 0, 0));
    const endOfDay = new Date(targetDate.setHours(23, 59, 59, 999));

    const sales = await Sales.find({
      salesDate: { $gte: startOfDay, $lte: endOfDay },
    }).populate('productId', 'productName category');

    const totalRevenue = sales.reduce((sum, s) => sum + s.soldTotalPrice, 0);
    const totalItems = sales.reduce((sum, s) => sum + s.soldQuantity, 0);

    res.json({
      date: startOfDay,
      sales,
      summary: {
        totalTransactions: sales.length,
        totalItemsSold: totalItems,
        totalRevenue,
      },
    });
  } catch (err) {
    res.status(500).json({ message: 'Error generating sales report', error: err.message });
  }
});

// Daily Stock Status Report
router.get('/daily-stock', requireAuth, async (req, res) => {
  try {
    const stocks = await StockStatus.find()
      .populate('productId', 'productName category unitPrice')
      .sort({ updatedAt: -1 });

    const report = stocks.map(s => ({
      productName: s.productId?.productName || 'N/A',
      category: s.productId?.category || 'N/A',
      storedQuantity: s.availableQuantity,
      soldQuantity: s.soldQuantity,
      remainingQuantity: s.remainingQuantity,
      status: s.remainingQuantity === 0
        ? 'Out of Stock'
        : s.remainingQuantity <= 5
        ? 'Low Stock'
        : 'In Stock',
    }));

    res.json({
      date: new Date(),
      report,
      summary: {
        totalProducts: report.length,
        outOfStock: report.filter(r => r.status === 'Out of Stock').length,
        lowStock: report.filter(r => r.status === 'Low Stock').length,
        inStock: report.filter(r => r.status === 'In Stock').length,
      },
    });
  } catch (err) {
    res.status(500).json({ message: 'Error generating stock report', error: err.message });
  }
});

module.exports = router;
