const Sales = require('../models/sales');
const Product = require('../models/product');
const Customer = require('../models/customer');

const sumTotal = (items, field) => items.reduce((total, item) => total + (item[field] || 0), 0);

exports.summary = async (req, res) => {
  try {
    const now = new Date();
    const startOfDay = new Date(now);
    startOfDay.setHours(0, 0, 0, 0);

    const startOfWeek = new Date(startOfDay);
    startOfWeek.setDate(startOfWeek.getDate() - startOfWeek.getDay());

    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);

    const [productCount, customerCount, salesCount] = await Promise.all([
      Product.countDocuments(),
      Customer.countDocuments(),
      Sales.countDocuments(),
    ]);

    const [dailySales, weeklySales, monthlySales] = await Promise.all([
      Sales.find({ salesDate: { $gte: startOfDay } }),
      Sales.find({ salesDate: { $gte: startOfWeek } }),
      Sales.find({ salesDate: { $gte: startOfMonth } }),
    ]);

    res.json({
      productCount,
      customerCount,
      salesCount,
      dailySalesTotal: sumTotal(dailySales, 'totalAmountPaid'),
      weeklySalesTotal: sumTotal(weeklySales, 'totalAmountPaid'),
      monthlySalesTotal: sumTotal(monthlySales, 'totalAmountPaid'),
      dailySalesCount: dailySales.length,
      weeklySalesCount: weeklySales.length,
      monthlySalesCount: monthlySales.length,
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
