"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUnitCostDifference = exports.getUnitCostDifferenceFull = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const decimal_js_1 = __importDefault(require("decimal.js"));
const collaterals_db_1 = require("../../db/collaterals.db");
const collaterals_enum_1 = require("../../enums/collaterals.enum");
const excel_helper_1 = require("../../helpers/excel.helper");
const inventories_db_1 = require("../../db/inventories.db");
const getUnitCostDifferenceFull = async (params) => {
    const data = await (0, exports.getUnitCostDifference)(params);
    const header = getUnitCostDifferenceHeader();
    return (0, excel_helper_1.addHeaderToData)(header, data);
};
exports.getUnitCostDifferenceFull = getUnitCostDifferenceFull;
const getUnitCostDifference = async (params) => {
    const { borrowerId } = params;
    const bbcGroups = await (0, collaterals_db_1.findCollateralsWithSheets)(borrowerId.toString(), [collaterals_enum_1.ECollaterals.INVENTORY]);
    const sheetIds = bbcGroups.reduce((acc, bbcGroup) => [...acc, ...bbcGroup.sheets.map((sheet) => new mongoose_1.default.Types.ObjectId(sheet._id))], []);
    const data = await (0, inventories_db_1.getSKUUnitCostForAllDates)(sheetIds);
    const mappedData = data.map((i) => {
        const difference = new decimal_js_1.default(i.currentCost).sub(i.minCost.minCost).toDP(4).toNumber();
        return {
            SKU: i._id,
            CURRENT_UNIT_COST: i.currentCost,
            LOWEST_UNIT_COST: i.minCost.minCost,
            LOWEST_UNIT_COST_DATE: i.minCost.bbcDate,
            DIFFERENCE: difference,
            CURRENT_QTY: i.qty,
            VALUE_CHANGE: new decimal_js_1.default(i.qty).mul(difference).toNumber(),
        };
    });
    return mappedData
        .filter((i) => i.DIFFERENCE > 0 || i.VALUE_CHANGE > 0)
        .sort((a, b) => a.VALUE_CHANGE > b.VALUE_CHANGE ? -1 : 0);
};
exports.getUnitCostDifference = getUnitCostDifference;
const getUnitCostDifferenceHeader = () => {
    return {
        SKU: 'SKU',
        CURRENT_QTY: 'qty',
        CURRENT_UNIT_COST: 'Current unit cost',
        LOWEST_UNIT_COST: 'Lowest unit cost',
        LOWEST_UNIT_COST_DATE: 'Lowest BBC date',
        DIFFERENCE: 'Difference',
        VALUE_CHANGE: 'Value change',
    };
};
