"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLastCollateralAdjustmentDocs = exports.copyCollateralAdjustmentWithoutSaving = exports.saveCollateralAdjustmentDoc = exports.getCollateralAdjustmentDocs = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const bbcDates_db_1 = require("./bbcDates.db");
const CollateralAdjustment_model_1 = require("../models/CollateralAdjustment.model");
const getCollateralAdjustmentDocs = async (bbcDateIds) => {
    return CollateralAdjustment_model_1.CollateralAdjustment.aggregate([
        {
            $match: {
                'bbcDateId': {
                    $in: bbcDateIds,
                },
            },
        },
    ]);
};
exports.getCollateralAdjustmentDocs = getCollateralAdjustmentDocs;
const saveCollateralAdjustmentDoc = async (bbcDateId, collateralAdjustmentUpdate) => {
    return CollateralAdjustment_model_1.CollateralAdjustment
        .findOneAndUpdate({ bbcDateId }, collateralAdjustmentUpdate, { upsert: true, new: true })
        .lean();
};
exports.saveCollateralAdjustmentDoc = saveCollateralAdjustmentDoc;
const copyCollateralAdjustmentWithoutSaving = async (bbcDateId, items, summary) => {
    return new CollateralAdjustment_model_1.CollateralAdjustment({ bbcDateId, items, summary });
};
exports.copyCollateralAdjustmentWithoutSaving = copyCollateralAdjustmentWithoutSaving;
const getLastCollateralAdjustmentDocs = async (bbcDateId, borrowerId) => {
    const bbcDates = await (0, bbcDates_db_1.getBBCDatesByBorrower)(borrowerId);
    const bbcDateIds = bbcDates.map((bbc) => bbc._id);
    return CollateralAdjustment_model_1.CollateralAdjustment.aggregate([
        {
            $match: {
                $and: [
                    { 'bbcDateId': { $in: bbcDateIds } },
                    { 'bbcDateId': { $ne: new mongoose_1.default.Types.ObjectId(bbcDateId) } },
                ],
            },
        },
        {
            $sort: { 'updatedAt': -1 },
        },
        {
            $limit: 1,
        },
    ]);
};
exports.getLastCollateralAdjustmentDocs = getLastCollateralAdjustmentDocs;
