"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.copyEquipmentWithoutSaving = exports.saveEquipmentDoc = exports.getLatestEquipments = exports.deleteEquipment = exports.getEquipment = exports.getEquipmentDates = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const Equipment_model_1 = __importDefault(require("../models/Equipment.model"));
const getEquipmentDates = async (borrowerId) => {
    return Equipment_model_1.default.aggregate([
        {
            $match: {
                'borrowerId': new mongoose_1.default.Types.ObjectId(borrowerId),
            },
        }, {
            $sort: { 'date': -1 },
        },
    ]);
};
exports.getEquipmentDates = getEquipmentDates;
const getEquipment = async (borrowerId, date) => {
    return Equipment_model_1.default.findOne({ 'borrowerId': new mongoose_1.default.Types.ObjectId(borrowerId), 'date': { $lte: date } }).lean();
};
exports.getEquipment = getEquipment;
const deleteEquipment = async (borrowerId, date) => {
    return Equipment_model_1.default.findOneAndDelete({ 'borrowerId': new mongoose_1.default.Types.ObjectId(borrowerId), 'date': date });
};
exports.deleteEquipment = deleteEquipment;
const getLatestEquipments = async (borrowerId, date) => {
    return Equipment_model_1.default.aggregate([
        {
            $match: {
                'borrowerId': new mongoose_1.default.Types.ObjectId(borrowerId),
                'date': { $lte: date },
            },
        }, {
            $sort: { 'date': -1 },
        }, {
            $limit: 1,
        },
    ]);
};
exports.getLatestEquipments = getLatestEquipments;
const saveEquipmentDoc = async (borrowerId, date, items, summary) => {
    return Equipment_model_1.default
        .findOneAndUpdate({ borrowerId: new mongoose_1.default.Types.ObjectId(borrowerId), date }, { items, summary }, { upsert: true, new: true })
        .lean();
};
exports.saveEquipmentDoc = saveEquipmentDoc;
const copyEquipmentWithoutSaving = async (borrower, date, items, summary) => {
    const notSavedEquipment = new Equipment_model_1.default({ borrower, date, items, summary });
    notSavedEquipment._id = null;
    return notSavedEquipment;
};
exports.copyEquipmentWithoutSaving = copyEquipmentWithoutSaving;
