"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getBrokerProducts = exports.getAllLoanBrokers = exports.getAllProductBrokers = exports.getBorrowerBrokers = exports.enrichWithBrokers = exports.getProductBrokers = void 0;
const decimal_js_1 = __importDefault(require("decimal.js"));
const mongoose_1 = __importDefault(require("mongoose"));
const _models_1 = require("../models/_models");
const reports_db_1 = require("./reports.db");
const ProductBroker_model_1 = require("../models/ProductBroker.model");
const LoanBroker_model_1 = require("../models/LoanBroker.model");
const getProductBrokers = async (productId) => {
    return ProductBroker_model_1.ProductBrokerModel.aggregate([
        {
            '$match': {
                'productId': new mongoose_1.default.Types.ObjectId(productId),
            },
        }, {
            $sort: { 'order': 1 },
        }, {
            $lookup: {
                from: _models_1.MODEL_NAMES.loanBrokers,
                localField: 'loanBrokerId',
                foreignField: '_id',
                as: 'loanBroker',
            },
        }, {
            $unwind: {
                path: '$loanBroker',
                preserveNullAndEmptyArrays: true,
            },
        }, {
            $unset: ['createdAt', 'updatedAt', '__v'],
        },
    ]);
};
exports.getProductBrokers = getProductBrokers;
const enrichWithBrokers = async (transactions, product) => {
    const productBrokers = await (0, exports.getProductBrokers)(product._id.toString());
    if (productBrokers.length === 0) {
        return transactions;
    }
    const handleFee = (t, broker, shareName) => {
        return {
            ...t,
            statementAmount: new decimal_js_1.default(-t.statementAmount).mul(broker[shareName]).toDP(2).toNumber(),
            title: `${t.title.replace('ACCRUED', '').trim()}: ${broker.loanBroker.name}`,
            chargeCode: broker.BSCode,
            PLCode: broker.PLCode,
            isBrokerFee: true,
        };
    };
    const handlers = {
        [reports_db_1.EChargeType.ADMIN_FEE]: (t, broker) => handleFee(t, broker, 'adminShare'),
        [reports_db_1.EChargeType.INTEREST_FEE]: (t, broker) => handleFee(t, broker, 'interestShare'),
        [reports_db_1.EChargeType.OTHER]: (t, broker) => handleFee(t, broker, 'otherShare'),
    };
    return transactions.reduce((acc, t) => {
        const handler = handlers[reports_db_1.EChargeType[t.type]];
        return handler ? [...acc, t, ...productBrokers.map((broker) => handler(t, broker))] : [...acc, t];
    }, []);
};
exports.enrichWithBrokers = enrichWithBrokers;
const getBorrowerBrokers = async (borrowerId) => {
    return ProductBroker_model_1.ProductBrokerModel
        .find({ borrowerId }, { createdAt: 0, updatedAt: 0, __v: 0 })
        .sort({ order: 1 })
        .lean();
};
exports.getBorrowerBrokers = getBorrowerBrokers;
const getAllProductBrokers = async () => {
    return ProductBroker_model_1.ProductBrokerModel
        .find({}, { createdAt: 0, updatedAt: 0, __v: 0 })
        .sort({ order: 1 })
        .lean();
};
exports.getAllProductBrokers = getAllProductBrokers;
const getAllLoanBrokers = async () => {
    const results = await LoanBroker_model_1.LoanBrokerModel
        .find({}, { createdAt: 0, updatedAt: 0, __v: 0 })
        .sort({ order: 1 })
        .lean();
    return results.map((result) => ({
        ...result,
        emails: result.emails ?? [],
    }));
};
exports.getAllLoanBrokers = getAllLoanBrokers;
const getBrokerProducts = async (loanBrokerId) => {
    return ProductBroker_model_1.ProductBrokerModel
        .find({ loanBrokerId }, { createdAt: 0, updatedAt: 0, __v: 0 })
        .sort({ order: 1, BSCode: 1, PLCode: 1 })
        .lean();
};
exports.getBrokerProducts = getBrokerProducts;
