import _ from 'lodash';
import dayjs from 'dayjs';

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

interface ISalesLocal {
  bbcDate: Date;
  sku: string;
  skuName: string;
  unitsSold: number;
  unitsCost?: number;
  unitSalePrice?: number;
  salesPeriodStart?: Date;
  salesPeriodEnd?: Date;
  salesPerDay?: number;
}

export class SalesItem implements ISalesLocal {

  bbcDate: Date = null;
  sku: string = '';
  skuName: string = '';
  unitsSold: number = 0;
  unitsCost: number = 0;
  unitSalePrice: number = 0;
  salesPeriodStart: Date | null = null;
  salesPeriodEnd: Date | null = null;
  salesPerDay?: number | null = null;

  constructor(item: Partial<SalesItem>, bbcDate = null, options: { [extraOption: string]: string }) {
    if (options && options.salesPeriodStart) {
      item.salesPeriodStart = dayjs.utc(options.salesPeriodStart).toDate();
    }
    if (options && options.salesPeriodEnd) {
      item.salesPeriodEnd = dayjs.utc(options.salesPeriodEnd).toDate();
    }
    const salesPeriod = dayjs.utc(item.salesPeriodEnd).diff(dayjs.utc(item.salesPeriodStart), 'day') + 1;
    if (typeof item.unitsSold === 'number') {
      this.salesPerDay = (salesPeriod !== 0 && item.unitsSold !== 0)
        ? new Decimal(item.unitsSold).div(salesPeriod).toDP(3).toNumber()
        : 0;
    }
    const itemWithDates = convertIntoDates(item, ECollaterals.SALES);
    const itemWithoutNulls = _.omitBy(itemWithDates, (value) => value === null);
    Object.assign(this, itemWithoutNulls);
    this.bbcDate = bbcDate;
  }
}
