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

export const getInvoiceDifferenceFull = async (params: TQueryParams) => {
  const { addedInvoices, removedInvoices } = await getInvoiceDifference(params);
  const header = getInvoiceDifferenceHeader();

  const addedInvoicesFull = addHeaderToData(header, addedInvoices);
  const removedInvoicesFull = addHeaderToData(header, removedInvoices);

  return { 'added': addedInvoicesFull, 'removed': removedInvoicesFull };
};

export const getInvoiceDifference = async (params: TQueryParams) => {
  const { bbcDateId } = params;
  const currentBbcDate = await BBCDateModel.findById(bbcDateId);
  if (currentBbcDate) {
    const previousDocuments = await getPreviousCollateralDocument(currentBbcDate.borrowerId.toString(), currentBbcDate.bbcDate, ECollaterals.RECEIVABLE, 1);
    const items1 = await getCollateralListByBBCAndType(currentBbcDate._id.toString(), ECollaterals.RECEIVABLE);
    const items2 = await getCollateralListByBBCAndType(previousDocuments[0]._id.toString(), ECollaterals.RECEIVABLE);
    return compareInvoices(items1, items2.length ? items2 : []);
  }
  return { addedInvoices: [], removedInvoices: [] };
};

const getInvoiceDifferenceHeader = () => {
  return {
    bbcDate: 'BBC date',
    customerTitle: 'Customer',
    dueDate: 'Due date',
    invoiceAmount: 'Invoice amount',
    originalAmount: 'Original amount',
    invoiceDate: 'Invoice date',
    invoiceNumber: 'Invoice number',
    invoiceDetail1: 'Invoice detail 1',
    invoiceDetail2: 'Invoice detail 2',
    invoiceDetail3: 'Invoice detail 3',
  };
};
