const express = require('express');
const Supplier = require('../models/Supplier');
const Shipment = require('../models/Shipment');
const Delivery = require('../models/Delivery');
const { protect } = require('../middleware/auth');
const { getDateRange } = require('../utils/dates');

const router = express.Router();

router.get('/:period', protect, async (req, res) => {
  try {
    const period = req.params.period;

    if (!['daily', 'weekly', 'monthly'].includes(period)) {
      return res.status(400).json({ message: 'Period must be daily, weekly, or monthly' });
    }

    const { start, end } = getDateRange(period);

    const [suppliers, shipments, deliveries] = await Promise.all([
      Supplier.find({ createdAt: { $gte: start, $lte: end } }).sort({ createdAt: -1 }),
      Shipment.find({ shipmentDate: { $gte: start, $lte: end } }).sort({ shipmentDate: -1 }),
      Delivery.find({ deliveryDate: { $gte: start, $lte: end } }).sort({ deliveryDate: -1 }),
    ]);

    const totalQuantity = deliveries.reduce((sum, d) => sum + d.quantityDelivered, 0);

    res.json({
      period,
      dateRange: { start, end },
      summary: {
        totalSuppliers: suppliers.length,
        totalShipments: shipments.length,
        totalDeliveries: deliveries.length,
        totalQuantityDelivered: totalQuantity,
      },
      suppliers,
      shipments,
      deliveries,
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router;
