"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLoanTransactions = exports.getLastTransactionForDate = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const LoanTransaction_model_1 = require("../models/LoanTransaction.model");
const loan_products_db_1 = require("./loan-products.db");
const collaterals_db_1 = require("./collaterals.db");
const getLastTransactionForDate = async (productId, date = new Date(), excludeAdjustments = false) => {
    const excludeFilter = excludeAdjustments
        ? {
            'transactionType': {
                $nin: ['ADJUSTMENT'],
            },
        }
        : {};
    const lastTransaction = await LoanTransaction_model_1.LoanTransaction.aggregate([
        {
            $match: {
                'productId': new mongoose_1.default.Types.ObjectId(productId),
                'date': { $lte: date },
                ...excludeFilter,
            },
        }, {
            $sort: {
                'date': -1,
                'order': -1,
                'createdAt': -1,
            },
        }, {
            $limit: 1,
        },
    ]);
    if (!lastTransaction.length) {
        return null;
    }
    return lastTransaction[0];
};
exports.getLastTransactionForDate = getLastTransactionForDate;
const getLoanTransactions = async (transactionsFilter, paginatorOptions, withBanks, isReverse = false, isMinified = false) => {
    const borrowerProducts = await (0, loan_products_db_1.getLoanProducts)(transactionsFilter.borrowerId);
    const productIds = borrowerProducts
        .filter((product) => transactionsFilter.productId ? product._id.toString() === transactionsFilter.productId : true)
        .map((product) => product._id);
    const optionalFilters = [];
    if (transactionsFilter.amount) {
        optionalFilters.push({ 'amount': transactionsFilter.amount });
    }
    if (transactionsFilter.reference) {
        optionalFilters.push({ 'reference': { $regex: transactionsFilter.reference, $options: 'i' } });
    }
    const bankLookup = !withBanks
        ? []
        : [
            {
                $lookup: {
                    from: 'banks',
                    localField: 'bankId',
                    foreignField: '_id',
                    as: 'bank',
                },
            }, {
                $unwind: {
                    path: '$bank',
                    preserveNullAndEmptyArrays: true,
                },
            },
        ];
    const projectedFields = isMinified
        ? [{ $project: { _id: 1, date: 1, amount: 1, reference: 1, balance: 1, transactionType: 1 } }]
        : [];
    return LoanTransaction_model_1.LoanTransaction.aggregate([
        {
            $match: {
                $and: [
                    { 'date': { $gte: transactionsFilter.periodStart } },
                    { 'date': { $lte: transactionsFilter.periodEnd } },
                    { 'productId': { $in: productIds } },
                    ...optionalFilters,
                ],
            },
        }, {
            $sort: {
                'date': isReverse ? -1 : 1,
                'order': isReverse ? -1 : 1,
                'createdAt': isReverse ? -1 : 1,
            },
        },
        ...(0, collaterals_db_1.ITEMS_PAGINATION)(paginatorOptions),
        ...bankLookup,
        {
            $unset: loan_products_db_1.fieldsToUnset,
        },
        ...projectedFields,
    ]);
};
exports.getLoanTransactions = getLoanTransactions;
