import * as saleRepo from '../repositories/saleRepository.js';
import * as productRepo from '../repositories/productRepository.js';
import Product from '../models/Product.js';
import { allVariantRows } from '../utils/variantUtils.js';

const getStats = async () => {
  const [today, totalProducts, recent, salesChart] =
    await Promise.all([
      saleRepo.getTodaySales(),
      productRepo.countDocuments(),
      saleRepo.findAll({ limit: 5 }),
      saleRepo.getSalesChart(7),
    ]);

  const products = await Product.find();
  const variantRows = allVariantRows(products);
  const lowStockVariants = variantRows.filter((r) => r.status === 'LOW_STOCK');
  const outOfStockVariants = variantRows.filter((r) => r.status === 'OUT_OF_STOCK');

  return {
    todaySales: today.totalSales,
    todayBills: today.count,
    totalProducts,
    totalStock: variantRows.reduce((s, r) => s + r.currentStock, 0),
    lowStockCount: lowStockVariants.length,
    outOfStockCount: outOfStockVariants.length,
    recentSales: recent.sales,
    lowStockProducts: lowStockVariants.slice(0, 5).map((r) => ({
      _id: r.productId,
      name: r.productName,
      category: r.category,
      image: r.image,
      trackingType: r.trackingType,
      currentStock: r.currentStock,
      lowStockThreshold: r.lowStockThreshold,
      variantLabel: r.variantLabel,
      sellingUnit: r.sellingUnit,
    })),
    salesChart: salesChart.map((c) => ({ date: c._id, sales: c.totalSales })),
  };
};

export default { getStats };