"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFinancialSpreadingData = exports.getCreateAllBorrowerSheet = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const lodash_1 = __importDefault(require("lodash"));
const FinancialSpreading_model_1 = require("../models/FinancialSpreading.model");
const date_helper_1 = require("../helpers/date.helper");
const FinancialSpreadingSheet_model_1 = require("../models/FinancialSpreadingSheet.model");
const db_data_helper_1 = require("../helpers/db-data.helper");
const getAllBorrowerSheets = async (params) => {
    const allSheets = await FinancialSpreadingSheet_model_1.FinancialSpreadingSheet.find({
        borrowerId: params.borrowerId,
        financialSpreadingType: params.financialSpreadingType,
    }).lean();
    return lodash_1.default.sortBy(allSheets, ['order', 'isTotal', 'suborder']);
};
const getCreateAllBorrowerSheet = async (params) => {
    const allSheets = await getAllBorrowerSheets(params);
    if (allSheets.length) {
        return allSheets;
    }
    const totalsMap = {
        [FinancialSpreadingSheet_model_1.EFinancialSpreadingType.PROFIT_LOSS]: FinancialSpreadingSheet_model_1.EFinanceSpreadingPLTotal,
        [FinancialSpreadingSheet_model_1.EFinancialSpreadingType.BALANCE_SHEET]: FinancialSpreadingSheet_model_1.EFinanceSpreadingBSTotal,
    };
    await Promise.all(Object.entries(FinancialSpreadingSheet_model_1.financeSpreadingLists[params.financialSpreadingType]).map(async ([totalKey, isCalculated], order) => {
        const newPartialRow = {
            borrowerId: new mongoose_1.default.Types.ObjectId(params.borrowerId),
            financialSpreadingType: params.financialSpreadingType,
            name: FinancialSpreadingSheet_model_1.financialSpreadingTotalDictionary[totalKey],
            rowType: totalsMap[params.financialSpreadingType][totalKey],
            isCalculated,
            order,
            suborder: 0,
        };
        if (!isCalculated) {
            const newRow = {
                ...newPartialRow,
                name: FinancialSpreadingSheet_model_1.financialSpreadingTotalDictionary[totalKey].toLowerCase(),
                isTotal: false,
            };
            const newRowItem = new FinancialSpreadingSheet_model_1.FinancialSpreadingSheet(newRow);
            await newRowItem.save();
        }
        const newTotalRow = {
            ...newPartialRow,
            isTotal: true,
        };
        const newTotalRowItem = new FinancialSpreadingSheet_model_1.FinancialSpreadingSheet(newTotalRow);
        await newTotalRowItem.save();
    }));
    return getAllBorrowerSheets(params);
};
exports.getCreateAllBorrowerSheet = getCreateAllBorrowerSheet;
const getClearData = (rawData, rawSheets) => {
    const data = (0, db_data_helper_1.rawDataToDTO)(FinancialSpreading_model_1.FinancialSpreadingDTO, rawData);
    const sheets = (0, db_data_helper_1.rawDataToDTO)(FinancialSpreadingSheet_model_1.FinancialSpreadingSheetDTO, rawSheets);
    return { data, sheets };
};
const getFinancialSpreadingData = async (params, monthDeep = 3) => {
    const validationRes = FinancialSpreading_model_1.financialSpreadingParamsValidationSchema.validate(params);
    if (validationRes.error) {
        console.error(validationRes.error);
        return { data: [], sheets: [] };
    }
    const range = Array.from({ length: monthDeep }, (_, i) => i + 1);
    const shifts = range.reduce((acc, curr) => {
        acc[`minus_${curr}`] = -curr;
        return acc;
    }, { 'amount': 0 });
    const rawSheets = await (0, exports.getCreateAllBorrowerSheet)(params);
    const rawData = await Promise.all(rawSheets.map(async (sheet) => {
        const combinedData = {
            _id: '',
            borrowerId: params.borrowerId,
            sheetId: sheet._id.toString(),
            year: params.selectedMonth.year,
            month: params.selectedMonth.month,
            amount: 0,
            minus_1: 0,
            minus_2: 0,
            minus_3: 0,
        };
        await Promise.all(Object.entries(shifts).map(async ([shiftName, shiftValue]) => {
            const filter = {
                borrowerId: params.borrowerId,
                sheetId: sheet._id,
                ...(0, date_helper_1.getShiftedMonth)(params.selectedMonth, shiftValue),
            };
            const foundData = await FinancialSpreading_model_1.FinancialSpreading.findOne(filter).lean();
            if (shiftValue === 0) {
                combinedData._id = foundData ? foundData._id.toString() : `new_${sheet._id}`;
            }
            combinedData[shiftName] = foundData ? foundData.amount : 0;
        }));
        return combinedData;
    }));
    return getClearData(rawData, rawSheets);
};
exports.getFinancialSpreadingData = getFinancialSpreadingData;
