import _ from 'lodash';

import { ECollaterals } from '../../enums/collaterals.enum';
import { getCollateralListByBBCAndType, getPreviousCollateralDocument } from '../../db/collaterals.db';
import { BBCDateModel } from '../../models/BBCDate.model';
import { TQueryParams } from '../../models/QueryResult.model';
import { addHeaderToData } from '../../helpers/excel.helper';

export const getInventoryDifferenceFull = async (params: TQueryParams) => {
  const { addedInventories, removedInventories } = await getInventoryDifference(params);
  const headerAdded = getInventoryDifferenceHeader();
  const headerRemoved = getInventoryDifferenceHeader();

  const addedInventoriesFull = addHeaderToData(headerAdded, addedInventories);
  const removedInventoriesFull = addHeaderToData(headerRemoved, removedInventories);

  return { 'added': addedInventoriesFull, 'removed': removedInventoriesFull };
};

export const getInventoryDifference = async (params: TQueryParams) => {
  const { bbcDateId } = params;
  const currentBbcDate = await BBCDateModel.findById(bbcDateId).lean();
  if (currentBbcDate) {
    const previousDocuments = await getPreviousCollateralDocument(currentBbcDate.borrowerId.toString(), currentBbcDate.bbcDate, ECollaterals.INVENTORY, 1);
    if (previousDocuments.length === 0) {
      return { addedInventories: [], removedInventories: [] };
    }
    const items1 = await getCollateralListByBBCAndType(currentBbcDate._id.toString(), ECollaterals.INVENTORY);
    const items2 = await getCollateralListByBBCAndType(previousDocuments[0]._id.toString(), ECollaterals.INVENTORY);
    const compareInventories = (items1: any[], items2: any[]) => {
      const addedInventories = _.differenceBy(items1, items2, 'sku');
      const removedInventories = _.differenceBy(items2, items1, 'sku');
      return { addedInventories, removedInventories };
    };
    return compareInventories(items1, items2);
  }
  return { addedInventories: [], removedInventories: [] };
};

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',
  };
};
