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

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

export const findBySale = async (saleId) =>
  SaleReturn.find({ sale: saleId }).sort('-createdAt');

export const findById = async (id) => SaleReturn.findById(id);

export const findLatest = async () => SaleReturn.findOne().sort('-createdAt');

export const aggregateReturnedByVariant = async (saleId, session) => {
  const results = await SaleReturn.aggregate(
    [
      { $match: { sale: saleId } },
      { $unwind: '$items' },
      {
        $group: {
          _id: { product: '$items.product', variantId: '$items.variantId' },
          quantity: { $sum: '$items.quantity' },
        },
      },
    ],
    { session }
  );
  const map = {};
  for (const r of results) {
    const key = `${r._id.product}_${r._id.variantId || ''}`;
    map[key] = (map[key] || 0) + r.quantity;
  }
  return map;
};

export const sumRefundsBetween = async (start, end) => {
  const result = await SaleReturn.aggregate([
    { $match: { createdAt: { $gte: start, $lte: end } } },
    { $group: { _id: null, total: { $sum: '$totalRefund' }, count: { $sum: 1 } } },
  ]);
  return result[0] || { total: 0, count: 0 };
};

export const aggregateDailyRefunds = async (start, end) =>
  SaleReturn.aggregate([
    { $match: { createdAt: { $gte: start, $lte: end } } },
    {
      $group: {
        _id: { $dateToString: { format: '%Y-%m-%d', date: '$createdAt' } },
        total: { $sum: '$totalRefund' },
      },
    },
    { $sort: { _id: 1 } },
  ]);

export const aggregateReturnedQuantities = async (start, end) =>
  SaleReturn.aggregate([
    { $match: { createdAt: { $gte: start, $lte: end } } },
    { $unwind: '$items' },
    {
      $group: {
        _id: '$items.product',
        name: { $first: '$items.productName' },
        quantity: { $sum: '$items.quantity' },
      },
    },
  ]);

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