import StockHistory from '../models/StockHistory.js';

export const findAll = async ({ product, type, variant, page = 1, limit = 20 }) => {
  const query = {};
  if (product) query.product = product;
  if (type) query.type = type;
  if (variant) query.variant = variant;

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

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

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