import * as saleRepo from '../repositories/saleRepository.js';
import * as productRepo from '../repositories/productRepository.js';

const getDailySales = async (date) => {
  const d = new Date(date);
  const start = new Date(d);
  start.setHours(0, 0, 0, 0);
  const end = new Date(d);
  end.setHours(23, 59, 59, 999);
  const result = await saleRepo.aggregateSales(start, end);
  const daily = await saleRepo.aggregateDailySales(start, end);
  return { ...(result[0] || { totalSales: 0, count: 0, totalDiscount: 0 }), daily };
};

const getWeeklySales = async (startDate) => {
  const start = new Date(startDate);
  start.setDate(start.getDate() - 6);
  start.setHours(0, 0, 0, 0);
  const end = new Date();
  end.setHours(23, 59, 59, 999);
  const result = await saleRepo.aggregateSales(start, end);
  const summary = result[0] || { totalSales: 0, count: 0, totalDiscount: 0 };
  const daily = await saleRepo.aggregateDailySales(start, end);
  return { ...summary, daily };
};

const getMonthlySales = async (year, month) => {
  const start = new Date(year, month - 1, 1);
  const end = new Date(year, month, 0, 23, 59, 59, 999);
  const result = await saleRepo.aggregateSales(start, end);
  const summary = result[0] || { totalSales: 0, count: 0, totalDiscount: 0 };
  const daily = await saleRepo.aggregateDailySales(start, end);
  return { ...summary, daily };
};

const getBestSelling = async (limit = 10) => {
  return saleRepo.bestSelling(limit);
};

const getLowStockReport = async () => {
  return productRepo.findLowStock();
};

export default { getDailySales, getWeeklySales, getMonthlySales, getBestSelling, getLowStockReport };
