const express = require('express');
const Customer = require('../models/Customer');
const Product = require('../models/Product');
const Sale = require('../models/Sale');
const router = express.Router();

const getStartOfPeriod = (period) => {
  const now = new Date();
  const start = new Date(now);
  if (period === 'weekly') {
    const diff = now.getDay();
    start.setDate(now.getDate() - diff);
  } else if (period === 'monthly') {
    start.setDate(1);
  }
  start.setHours(0, 0, 0, 0);
  return start;
};

router.get('/', async (req, res) => {
  try {
    const period = req.query.period || 'daily';
    const customers = await Customer.countDocuments();
    const products = await Product.countDocuments();
    const sales = await Sale.find();

    const totalSales = sales.reduce((sum, sale) => sum + Number(sale.totalAmountPaid), 0);
    const periodStart = period === 'daily' ? new Date(new Date().setHours(0, 0, 0, 0)) : getStartOfPeriod(period);

    const filtered = sales.filter((sale) => new Date(sale.salesDate) >= periodStart);
    const periodSalesTotal = filtered.reduce((sum, sale) => sum + Number(sale.totalAmountPaid), 0);

    res.json({
      customerCount: customers,
      productCount: products,
      salesCount: sales.length,
      totalSalesAmount: totalSales,
      periodSalesCount: filtered.length,
      periodSalesAmount: periodSalesTotal,
      period,
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router;
