import _ from 'lodash';

import { convertIntoDates } from '../helpers/column-desciptions.helper';
import { ECollaterals } from '../enums/collaterals.enum';

interface IInventoryItemLocal {
  bbcDate: Date;
  sku: number;
  lotNumber: number;
  category: string;
  location: string;
  skuDescription1: string;
  skuDescription2: string;
  skuDescription3: string;
  detail1: string;
  detail2: string;
  detail3: string;
  skuDate: Date;
  expiryDate: string;
  qty: number;
  unitCost: number;
  value: number;
}

export class InventoryItem implements IInventoryItemLocal {
  bbcDate: Date = null;
  category: string = 'NO CATEGORY';
  expiryDate: string = '';
  location: string = '';
  lotNumber: number = 0;
  qty: number = 1;
  sku: number = 0;
  skuDate: Date = null;
  skuDescription1: string = '';
  skuDescription2: string = '';
  skuDescription3: string = '';
  detail1: string = '';
  detail2: string = '';
  detail3: string = '';
  unitCost: number = 0;
  value: number = 0;

  constructor(
    item: Partial<InventoryItem>,
    bbcDate = null,
    skuDates: { _id: string; oldestDate: string }[] = [],
  ) {
    const itemWithDates = convertIntoDates(item, ECollaterals.INVENTORY);
    const itemWithoutNulls = _.omitBy(itemWithDates, (value) => value === null);
    Object.assign(this, itemWithoutNulls);
    this.bbcDate = bbcDate;
    if (!this.skuDate && item.sku) {
      const previousSKUDate = skuDates.find((d) => item.sku.toString().trim() === d._id);
      if (!previousSKUDate) {
        this.skuDate = this.bbcDate;
      } else {
        const isPreviousDateGreaterThanSubmittedDate = new Date(previousSKUDate.oldestDate).getTime() > new Date(this.bbcDate).getTime();
        this.skuDate = isPreviousDateGreaterThanSubmittedDate ? this.bbcDate : new Date(previousSKUDate.oldestDate);
      }
    }
  }

}
