"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoanTransaction = exports.LoanTransactionSchema = exports.LOAN_TRANSACTION_FIELDS = exports.LOAN_TRANSACTION_DOWNLOAD_FIELDS = exports.ELoanTransactionTypes = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const _models_1 = require("./_models");
const UserLog_model_1 = require("./UserLog.model");
const DeletedRecords_model_1 = require("./DeletedRecords.model");
const user_logs_db_1 = require("../db/user-logs.db");
var ELoanTransactionTypes;
(function (ELoanTransactionTypes) {
    ELoanTransactionTypes["COLLECTION"] = "COLLECTION";
    ELoanTransactionTypes["DISBURSEMENT"] = "DISBURSEMENT";
    ELoanTransactionTypes["ADJUSTMENT"] = "ADJUSTMENT";
    ELoanTransactionTypes["CHARGE"] = "CHARGE";
})(ELoanTransactionTypes || (exports.ELoanTransactionTypes = ELoanTransactionTypes = {}));
exports.LOAN_TRANSACTION_DOWNLOAD_FIELDS = [
    'date',
    'amount',
    'description',
    'reference',
    'customerId',
    'transactionType',
];
exports.LOAN_TRANSACTION_FIELDS = [
    '_id',
    'date',
    'effectiveDate',
    'productId',
    'chargeId',
    'amount',
    'description',
    'reference',
    'customerId',
    'bankId',
    'transactionType',
    'balance',
    'floatedBalance',
    'loanPaymentId',
    'userId',
];
exports.LoanTransactionSchema = new mongoose_1.default.Schema({
    userId: {
        type: String,
        required: false,
    },
    order: {
        type: Number,
        required: true,
        default: 0,
    },
    date: {
        type: Date,
        required: true,
    },
    effectiveDate: {
        type: Date,
        required: true,
    },
    productId: {
        type: mongoose_1.default.Schema.Types.ObjectId,
        ref: _models_1.MODEL_NAMES.loanProducts,
        required: true,
    },
    chargeId: {
        type: mongoose_1.default.Schema.Types.ObjectId,
        ref: _models_1.MODEL_NAMES.loanCharges,
        required: false,
    },
    amount: {
        type: Number,
        required: true,
    },
    description: {
        type: String,
        trim: true,
    },
    reference: {
        type: String,
        trim: true,
    },
    referenceRaw: {
        type: String,
        trim: true,
        required: false,
    },
    customerId: {
        type: String,
        trim: true,
    },
    bankId: {
        type: mongoose_1.default.Schema.Types.ObjectId,
        ref: _models_1.MODEL_NAMES.banks,
        required: false,
    },
    transactionType: {
        type: String,
        enum: Object.values(ELoanTransactionTypes),
        required: true,
    },
    balance: {
        type: Number,
    },
    floatedBalance: {
        type: Number,
    },
    loanPaymentId: {
        type: mongoose_1.default.Schema.Types.ObjectId,
        ref: 'loan_payments',
    },
    isSent: {
        type: Boolean,
        required: false,
    },
}, { timestamps: true });
exports.LoanTransactionSchema.statics.findByIdAndDeleteWithUserId = async function (id, userId) {
    const foundDoc = await this.findById(id).lean();
    if (!foundDoc) {
        return this.findByIdAndDelete(id);
    }
    const deletedRecord = new DeletedRecords_model_1.DeletedRecord({
        DBCollection: 'loan_transactions',
        recordId: id,
        record: foundDoc,
    });
    await deletedRecord.save();
    await (0, user_logs_db_1.createLog)({
        action: UserLog_model_1.ELogActionType.DELETE,
        logType: UserLog_model_1.ELogType.LOAN_TRANSACTION,
        userId: userId,
        recordCollection: 'loan_transactions',
        recordId: id,
        details: {},
    });
    return this.findByIdAndDelete(id);
};
exports.LoanTransactionSchema.pre(/^(save)/, async function () {
    const myDoc = this;
    await (0, user_logs_db_1.createLog)({
        action: UserLog_model_1.ELogActionType.CREATE,
        logType: UserLog_model_1.ELogType.LOAN_TRANSACTION,
        userId: myDoc.userId,
        recordCollection: 'loan_transactions',
        recordId: myDoc._id,
        details: {},
    });
});
exports.LoanTransactionSchema.pre(/^(updateOne|updateMany|findOneAndUpdate)/, async function () {
    const myDoc = this;
    const update = myDoc._update;
    const conditions = myDoc._conditions;
    if (update
        && update.hasOwnProperty('userId')
        && conditions
        && conditions.hasOwnProperty('_id')) {
        const oldDoc = await myDoc.model.findById(conditions._id);
        let changes = {};
        if (oldDoc) {
            changes = (0, user_logs_db_1.getLogChanges)(oldDoc, update);
        }
        await (0, user_logs_db_1.createLog)({
            action: UserLog_model_1.ELogActionType.EDIT,
            logType: UserLog_model_1.ELogType.LOAN_TRANSACTION,
            userId: update.userId,
            recordCollection: 'loan_transactions',
            recordId: conditions._id,
            details: {
                changes,
            },
        });
    }
});
exports.LoanTransaction = mongoose_1.default.model(_models_1.MODEL_NAMES.loanTransactions, exports.LoanTransactionSchema);
