"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getExtension = exports.getExtensionFull = void 0;
const dayjs_1 = __importDefault(require("dayjs"));
const excel_helper_1 = require("../../helpers/excel.helper");
const collaterals_db_1 = require("../../db/collaterals.db");
const collaterals_enum_1 = require("../../enums/collaterals.enum");
const inventories_db_1 = require("../../db/inventories.db");
const bbcDates_db_1 = require("../../db/bbcDates.db");
const bbcSheets_db_1 = require("../../db/bbcSheets.db");
const getExtensionFull = async (params) => {
    const data = await (0, exports.getExtension)(params);
    const firstRawKeys = data.length > 0 ? Object.keys(data[0]) : [];
    const header = getExtensionHeader(firstRawKeys);
    return (0, excel_helper_1.addHeaderToData)(header, data);
};
exports.getExtensionFull = getExtensionFull;
const getExtension = async (params) => {
    const { borrowerId, startDate, endDate } = params;
    const bbcDates = await (0, bbcDates_db_1.getBBCDatesForPeriod)(String(borrowerId), new Date(startDate), new Date(endDate));
    const bbcIds = bbcDates.map((bbc) => String(bbc._id));
    const BBCs = await (0, collaterals_db_1.getCollateralDocsByBBC)(bbcIds, collaterals_enum_1.ECollaterals.INVENTORY);
    const allInventoryBbcDates = await (0, bbcSheets_db_1.getUniqueDatesForPeriod)(String(borrowerId), collaterals_enum_1.ECollaterals.INVENTORY, new Date(startDate), new Date(endDate));
    const sheetIds = allInventoryBbcDates.reduce((acc, bbcGroup) => [...acc, ...bbcGroup.ids], []);
    const { skus } = (await (0, inventories_db_1.getAllUniqSKUInRangeNew)(sheetIds)).pop();
    const sortedSkus = skus.sort((a, b) => a > b ? 1 : -1);
    return sortedSkus.map((sku) => {
        const qty = BBCs.reduce((acc, bbc) => {
            const foundItem = bbc.items.find((item) => item.sku === sku);
            return { ...acc, [(0, dayjs_1.default)(bbc.bbcDate).format('DD-MM-YYYY')]: foundItem ? foundItem.qty : null };
        }, {});
        return { sku, ...qty };
    });
};
exports.getExtension = getExtension;
const getExtensionHeader = (firstRawKeys) => {
    return {
        sku: 'SKU',
        ...firstRawKeys
            .filter((key) => key !== 'sku')
            .reduce((acc, key) => ({ ...acc, [key]: key }), {}),
    };
};
