import Purchase from '../models/Purchase.js';
import Product from '../models/Product.js';

export const findAll = async ({ product, search, startDate, endDate, page = 1, limit = 20 }) => {
  const query = {};
  if (product) query.product = product;
  if (search) {
    const matchingProducts = await Product.find({ name: { $regex: search, $options: 'i' } }).select('_id');
    query.product = { $in: matchingProducts.map(p => p._id) };
  }
  if (startDate || endDate) {
    query.purchaseDate = {};
    if (startDate) query.purchaseDate.$gte = new Date(startDate);
    if (endDate) query.purchaseDate.$lte = new Date(endDate);
  }

  const skip = (Number(page) - 1) * Number(limit);
  const [purchases, total] = await Promise.all([
    Purchase.find(query)
      .populate('product', 'name category trackingType unit sizeSystem variants')
      .sort('-purchaseDate')
      .skip(skip)
      .limit(Number(limit)),
    Purchase.countDocuments(query),
  ]);

  return { purchases, total, page: Number(page), pages: Math.ceil(total / Number(limit)) };
};

export const findById = async (id) => Purchase.findById(id).populate('product', 'name category currentStock trackingType unit sizeSystem sizeVariants variants');

export const create = async (data, session) => {
  const purchase = new Purchase(data);
  await purchase.save({ session });
  return purchase;
};

export const countDocuments = async () => Purchase.countDocuments();
