import mongoose from 'mongoose';

import { AccountPayableItemModel, IAccountPayableItemDoc } from '../models/AccountPayableItem.model';
import { getBBCSheetsForBorrowerAndType } from './collaterals.db';
import { ECollaterals } from '../enums/collaterals.enum';

export const getAllAPCustomers = async (borrowerId: string) => {
  const bbcSheets = await getBBCSheetsForBorrowerAndType(borrowerId, ECollaterals.ACCOUNT_PAYABLE);
  return AccountPayableItemModel.aggregate<{ customers: string[] }>([
    {
      $match: {
        'bbcSheetId': {
          $in: bbcSheets.map((bbcSheet) => new mongoose.Types.ObjectId(String(bbcSheet._id)))
        }
      }
    },
    {
      $group: {
        '_id': null,
        'customers': {
          $addToSet: '$customerName'
        }
      }
    },
    {
      $project: {
        '_id': 0
      }
    },
  ]);
};

export const getBBCAPByAPPeriod = async (bbcSheetsIds: mongoose.Types.ObjectId[], rangeStart, rangeEnd) => {
  return AccountPayableItemModel.aggregate<IAccountPayableItemDoc>([
    {
      $match: {
        $and: [
          { 'bbcSheetId': { $in: bbcSheetsIds } },
          { 'apDate': { $gte: new Date(rangeStart) } },
          { 'apDate': { $lte: new Date(rangeEnd) } },
        ]
      }
    },
    {
      $sort: {
        'apDate': 1
      }
    },
  ]);
}
