const Supplier = require('../models/Supplier');
const Shipment = require('../models/shipment');
const Delivery = require('../models/delivery');

function getStartDate(days) {
  const date = new Date();
  date.setHours(0, 0, 0, 0);
  date.setDate(date.getDate() - days);
  return date;
}

exports.getReportSummary = async (req, res) => {
  try {
    const now = new Date();
    const dailyStart = getStartDate(1);
    const weeklyStart = getStartDate(7);
    const monthlyStart = getStartDate(30);

    const [
      totalSuppliers,
      dailySuppliers,
      weeklySuppliers,
      monthlySuppliers,
      totalShipments,
      dailyShipments,
      weeklyShipments,
      monthlyShipments,
      totalDeliveries,
      dailyDeliveries,
      weeklyDeliveries,
      monthlyDeliveries,
      recentShipments,
      recentDeliveries,
    ] = await Promise.all([
      Supplier.countDocuments(),
      Supplier.countDocuments({ createdAt: { $gte: dailyStart } }),
      Supplier.countDocuments({ createdAt: { $gte: weeklyStart } }),
      Supplier.countDocuments({ createdAt: { $gte: monthlyStart } }),
      Shipment.countDocuments(),
      Shipment.countDocuments({ createdAt: { $gte: dailyStart } }),
      Shipment.countDocuments({ createdAt: { $gte: weeklyStart } }),
      Shipment.countDocuments({ createdAt: { $gte: monthlyStart } }),
      Delivery.countDocuments(),
      Delivery.countDocuments({ createdAt: { $gte: dailyStart } }),
      Delivery.countDocuments({ createdAt: { $gte: weeklyStart } }),
      Delivery.countDocuments({ createdAt: { $gte: monthlyStart } }),
      Shipment.find().sort({ createdAt: -1 }).limit(5).populate('supplier'),
      Delivery.find().sort({ createdAt: -1 }).limit(5).populate({ path: 'shipment', populate: 'supplier' }),
    ]);

    res.status(200).json({
      suppliers: {
        total: totalSuppliers,
        daily: dailySuppliers,
        weekly: weeklySuppliers,
        monthly: monthlySuppliers,
      },
      shipments: {
        total: totalShipments,
        daily: dailyShipments,
        weekly: weeklyShipments,
        monthly: monthlyShipments,
      },
      deliveries: {
        total: totalDeliveries,
        daily: dailyDeliveries,
        weekly: weeklyDeliveries,
        monthly: monthlyDeliveries,
      },
      recentShipments,
      recentDeliveries,
      generatedAt: now,
    });
  } catch (error) {
    res.status(500).json({ msg: 'Failed to generate report', error: error.message });
  }
};
