import Decimal from 'decimal.js';

import { round } from '../../helpers/numbers.helper';
import { getSKUQtyValueUnitCost } from '../../db/inventories.db';
import { TQueryParams } from '../../models/QueryResult.model';
import { addHeaderToData } from '../../helpers/excel.helper';

export const getInconsistentDataFull = async (params: TQueryParams) => {
  const data = await getInconsistentData(params);
  const header = getInconsistentDataHeader();
  return addHeaderToData(header, data);
};

export const getInconsistentData = async (params: TQueryParams) => {
  const { bbcDateId } = params;
  const data = await getSKUQtyValueUnitCost(bbcDateId.toString());
  const formattedData = data.map((i) => {
    const calculatedUnitCost = 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(calculatedUnitCost).toDP(4).toNumber(),
      DIFFERENCE: difference,
      QTY: i.qty,
      VALUE_CHANGE: new Decimal(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);
};

const getInconsistentDataHeader = () => {
  return {
    SKU: 'SKU',
    UNIT_COST: 'Unit cost',
    CALCULATED_UNIT_COST: 'Calculated unit cost',
    DIFFERENCE: 'Difference',
    QTY: 'qty',
    VALUE_CHANGE: 'Value change',
  };
};
