"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getInventoryDifference = exports.getInventoryDifferenceFull = void 0;
const lodash_1 = __importDefault(require("lodash"));
const collaterals_enum_1 = require("../../enums/collaterals.enum");
const collaterals_db_1 = require("../../db/collaterals.db");
const BBCDate_model_1 = require("../../models/BBCDate.model");
const excel_helper_1 = require("../../helpers/excel.helper");
const getInventoryDifferenceFull = async (params) => {
    const { addedInventories, removedInventories } = await (0, exports.getInventoryDifference)(params);
    const headerAdded = getInventoryDifferenceHeader();
    const headerRemoved = getInventoryDifferenceHeader();
    const addedInventoriesFull = (0, excel_helper_1.addHeaderToData)(headerAdded, addedInventories);
    const removedInventoriesFull = (0, excel_helper_1.addHeaderToData)(headerRemoved, removedInventories);
    return { 'added': addedInventoriesFull, 'removed': removedInventoriesFull };
};
exports.getInventoryDifferenceFull = getInventoryDifferenceFull;
const getInventoryDifference = async (params) => {
    const { bbcDateId } = params;
    const currentBbcDate = await BBCDate_model_1.BBCDateModel.findById(bbcDateId).lean();
    if (currentBbcDate) {
        const previousDocuments = await (0, collaterals_db_1.getPreviousCollateralDocument)(currentBbcDate.borrowerId.toString(), currentBbcDate.bbcDate, collaterals_enum_1.ECollaterals.INVENTORY, 1);
        if (previousDocuments.length === 0) {
            return { addedInventories: [], removedInventories: [] };
        }
        const items1 = await (0, collaterals_db_1.getCollateralListByBBCAndType)(currentBbcDate._id.toString(), collaterals_enum_1.ECollaterals.INVENTORY);
        const items2 = await (0, collaterals_db_1.getCollateralListByBBCAndType)(previousDocuments[0]._id.toString(), collaterals_enum_1.ECollaterals.INVENTORY);
        const compareInventories = (items1, items2) => {
            const addedInventories = lodash_1.default.differenceBy(items1, items2, 'sku');
            const removedInventories = lodash_1.default.differenceBy(items2, items1, 'sku');
            return { addedInventories, removedInventories };
        };
        return compareInventories(items1, items2);
    }
    return { addedInventories: [], removedInventories: [] };
};
exports.getInventoryDifference = getInventoryDifference;
const getInventoryDifferenceHeader = () => {
    return {
        bbcDate: 'BBC date',
        category: 'Category',
        sku: 'SKU',
        expiryDate: 'Expiry date',
        qty: 'Quantity',
        unitCost: 'Unit amount',
        value: 'Value',
        skuDescription1: 'SKU description 1',
        skuDescription2: 'SKU description 2',
        skuDescription3: 'SKU description 3',
    };
};
