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