"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoanStatementEffectsService = void 0;
const dayjs_1 = __importDefault(require("dayjs"));
const mongoose_1 = __importDefault(require("mongoose"));
const loan_products_db_1 = require("../db/loan-products.db");
const MonthEndData_Model_1 = require("../models/MonthEndData.Model");
class LoanStatementEffectsService {
    loanStatementBalanceService;
    monthEndDataService;
    constructor(loanStatementBalanceService, monthEndDataService) {
        this.loanStatementBalanceService = loanStatementBalanceService;
        this.monthEndDataService = monthEndDataService;
    }
    async saveMonthData(productId, statementDate) {
        if ((0, dayjs_1.default)(statementDate).date() !== 1) {
            return;
        }
        const balance = await (0, loan_products_db_1.getLoanProductBalance)(productId, statementDate);
        const lastTransaction = await this.loanStatementBalanceService.getLastStatementTransactionForDate(productId, statementDate);
        const month = (0, dayjs_1.default)(statementDate).subtract(1, 'd').month() + 1;
        const year = (0, dayjs_1.default)(statementDate).subtract(1, 'd').year();
        const keptData = {
            [MonthEndData_Model_1.EMonthEndDataType.BALANCE]: balance?.balance ?? 0,
            [MonthEndData_Model_1.EMonthEndDataType.FLOATED_BALANCE]: balance?.floatedBalance ?? 0,
            [MonthEndData_Model_1.EMonthEndDataType.STATEMENT_BALANCE]: lastTransaction?.balance ?? 0,
        };
        await Promise.all(Object.entries(keptData).map(async ([dataType, dataValue]) => {
            await this.monthEndDataService.upsertMonthEndData({
                productId: new mongoose_1.default.Types.ObjectId(productId),
                year,
                month,
                dataType: dataType,
                dataValue,
            });
        }));
    }
}
exports.LoanStatementEffectsService = LoanStatementEffectsService;
