"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getInconsistentData = exports.getInconsistentDataFull = void 0;
const decimal_js_1 = __importDefault(require("decimal.js"));
const numbers_helper_1 = require("../../helpers/numbers.helper");
const inventories_db_1 = require("../../db/inventories.db");
const excel_helper_1 = require("../../helpers/excel.helper");
const getInconsistentDataFull = async (params) => {
    const data = await (0, exports.getInconsistentData)(params);
    const header = getInconsistentDataHeader();
    return (0, excel_helper_1.addHeaderToData)(header, data);
};
exports.getInconsistentDataFull = getInconsistentDataFull;
const getInconsistentData = async (params) => {
    const { bbcDateId } = params;
    const data = await (0, inventories_db_1.getSKUQtyValueUnitCost)(bbcDateId.toString());
    const formattedData = data.map((i) => {
        const calculatedUnitCost = (0, numbers_helper_1.round)(i.value / i.qty);
        const difference = i.unitCost - calculatedUnitCost;
        if (i.qty === 0 || difference === 0)
            return;
        return {
            SKU: i._id.trim(),
            UNIT_COST: i.unitCost,
            CALCULATED_UNIT_COST: new decimal_js_1.default(calculatedUnitCost).toDP(4).toNumber(),
            DIFFERENCE: difference,
            QTY: i.qty,
            VALUE_CHANGE: new decimal_js_1.default(i.qty).mul(difference).toDP(4).toNumber(),
        };
    });
    return formattedData
        .filter((i) => i !== undefined && Math.abs(i.DIFFERENCE) >= 0.01)
        .sort((a, b) => a.VALUE_CHANGE > b.VALUE_CHANGE ? -1 : 0);
};
exports.getInconsistentData = getInconsistentData;
const getInconsistentDataHeader = () => {
    return {
        SKU: 'SKU',
        UNIT_COST: 'Unit cost',
        CALCULATED_UNIT_COST: 'Calculated unit cost',
        DIFFERENCE: 'Difference',
        QTY: 'qty',
        VALUE_CHANGE: 'Value change',
    };
};
