import dayjs from 'dayjs';

import { TQueryParams } from '../../models/QueryResult.model';
import { addHeaderToData } from '../../helpers/excel.helper';
import { getCollateralDocsByBBC } from '../../db/collaterals.db';
import { ECollaterals } from '../../enums/collaterals.enum';
import { getAllUniqSKUInRangeNew } from '../../db/inventories.db';
import { getBBCDatesForPeriod } from '../../db/bbcDates.db';
import { getUniqueDatesForPeriod } from '../../db/bbcSheets.db';

export const getExtensionFull = async (params: TQueryParams) => {
  const data = await getExtension(params);
  const firstRawKeys = data.length > 0 ? Object.keys(data[0]) : [];
  const header = getExtensionHeader(firstRawKeys);
  return addHeaderToData(header, data);
};

export const getExtension = async (params: TQueryParams) => {
  const { borrowerId, startDate, endDate } = params;
  const bbcDates = await getBBCDatesForPeriod(String(borrowerId), new Date(startDate), new Date(endDate));
  const bbcIds = bbcDates.map((bbc) => String(bbc._id));
  const BBCs = await getCollateralDocsByBBC(bbcIds, ECollaterals.INVENTORY);
  const allInventoryBbcDates = await getUniqueDatesForPeriod(String(borrowerId), ECollaterals.INVENTORY, new Date(startDate), new Date(endDate));
  const sheetIds = allInventoryBbcDates.reduce((acc, bbcGroup) => [...acc, ...bbcGroup.ids], []);
  const { skus } = (await getAllUniqSKUInRangeNew(sheetIds)).pop();
  const sortedSkus = skus.sort((a, b) => a > b ? 1 : -1);
  return sortedSkus.map((sku) => {
    const qty = BBCs.reduce((acc, bbc) => {
      const foundItem = bbc.items.find((item) => item.sku === sku);
      return { ...acc, [dayjs(bbc.bbcDate).format('DD-MM-YYYY')]: foundItem ? foundItem.qty : null };
    }, {});
    return { sku, ...qty };
  });
};

const getExtensionHeader = (firstRawKeys: string[]) => {
  return {
    sku: 'SKU',
    ...firstRawKeys
      .filter((key) => key !== 'sku')
      .reduce((acc, key) => ({ ...acc, [key]: key }), {}),
  };
};
