import { pipe } from 'core/tools/func';
import { ICalculationStore } from 'core/types/Calculation/Store';
import { Process } from 'core/types/Calculation/Store/process';
import { reaction } from 'mobx';

export default function ($calculation: ICalculationStore) {
  reaction(
    () => {
      return {
        product: $calculation.getOption('selectProduct'),
        ...$calculation.getValues([
          'leasingPeriod',
          'deliveryTime',
          'firstPaymentPerc',
          'lastPaymentPerc',
          'leaseObjectUsed',
        ]),
      };
    },
    ({
      product,
      leasingPeriod,
      deliveryTime,
      firstPaymentPerc,
      lastPaymentPerc,
      leaseObjectUsed,
    }) => {
      if (product && leasingPeriod && deliveryTime) {
        const target_tarif = $calculation.options.selectTarif?.find(
          pipe(
            tarif =>
              tarif.evo_baseproductid === product.evo_baseproductid &&
              tarif.evo_min_period <= leasingPeriod &&
              tarif.evo_max_period >= leasingPeriod &&
              tarif.evo_delivery_time?.includes(deliveryTime) &&
              tarif.evo_min_first_payment <= firstPaymentPerc &&
              tarif.evo_max_first_payment >= firstPaymentPerc &&
              tarif.evo_min_last_payment <= lastPaymentPerc &&
              tarif.evo_max_last_payment >= lastPaymentPerc &&
              tarif,
            tarif => {
              if (leaseObjectUsed === true) {
                if (tarif.evo_used) {
                  return tarif;
                }
              } else {
                return tarif;
              }
            },
          ),
        );

        $calculation.setValue('tarif', target_tarif?.evo_tarifid);
      } else {
        $calculation.setValue('tarif', null);
      }
    },
  );

  reaction(
    () => $calculation.values.tarif,
    tarifid => {
      const { calculationProcess } = $calculation.stores;
      if (calculationProcess.hasProcess(Process.LoadKp)) {
        return;
      }

      const tarif = $calculation.getOption('selectTarif', {
        evo_tarifid: tarifid,
      });

      $calculation.setValue('IRR_Perc', tarif?.evo_irr);
    },
  );
}
