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

export const getInvoiceMovementFull = async (params: TQueryParams) => {
  const { reportAdditions, reportRemoved } = await getInvoiceMovement(params);

  const headerAdditions = getUnitCostDifferenceHeader('additions');
  const headerRemoved = getUnitCostDifferenceHeader('removed');

  const tableAdditionsFull = addHeaderToData(headerAdditions, reportAdditions);
  const tableRemovedFull = addHeaderToData(headerRemoved, reportRemoved);

  return { 'additions': tableAdditionsFull, 'removed': tableRemovedFull };
};

export const getInvoiceMovement = async (params: TQueryParams) => {
  const { bbcDateId, borrowerId } = params;
  const currentBbcDate = await BBCDateModel.findById(bbcDateId);
  if (currentBbcDate) {
    const previousDocuments = await getPreviousCollateralDocument(currentBbcDate.borrowerId.toString(), currentBbcDate.bbcDate, ECollaterals.INVENTORY, 1);
    if (previousDocuments.length > 0) {
      return getInventoryMovement(borrowerId.toString(), previousDocuments[0].bbcDate.toString(), currentBbcDate.bbcDate.toString());
    }
  }
  return { reportAdditions: [], reportRemoved: [] };
};

export const getUnitCostDifferenceHeader = (type: 'additions' | 'removed') => {
  const headerMap = {
    'additions': {
      sku: 'SKU',
      previousValue: 'Previous',
      currentValue: 'Current',
      units: 'New units',
      value: 'Value increase',
    },
    'removed': {
      sku: 'SKU',
      previousValue: 'Previous',
      currentValue: 'Current',
      units: 'Removed units',
      value: 'Removed increase',
    },
  };
  return headerMap[type];
};
