import { reaction } from 'mobx';
import type { ReactionsContext } from 'process/types';

export default function validationReactions({ store }: ReactionsContext) {
  const { $calculation, $tables } = store;
  reaction(
    () => {
      const hasElementsErrors = Object.values($calculation.$validation).some(
        (validation) => validation.hasErrors
      );
      const hasPaymentsErrors = $tables.payments.validation.hasErrors;
      const hasInsuranceErrors = $tables.insurance.validation.hasErrors;
      const hasFingapErrors = $tables.fingap.validation.hasErrors;

      return hasElementsErrors || hasPaymentsErrors || hasInsuranceErrors || hasFingapErrors;
    },
    (hasErrors) => {
      if (hasErrors) {
        $calculation.$status.setStatus('btnCalculate', 'Disabled');
        $calculation.$status.setStatus('btnCreateKP', 'Disabled');
      } else {
        $calculation.$status.setStatus('btnCalculate', 'Default');
        $calculation.$status.setStatus('btnCreateKP', 'Default');
      }
    },
    {
      fireImmediately: true,
    }
  );
}
