/* eslint-disable @typescript-eslint/naming-convention */
import { gql } from '@apollo/client';
import type { GetTransactionCurrenciesQuery } from 'gql/crm.types';
import { when } from 'mobx';
import type { ReactionsContext } from 'process/types';

export default function setInitialValuesReactions({ store, apolloClient }: ReactionsContext) {
  const QUERY_GET_TRANSACTION_CURRENCIES = gql`
    query GetTransactionCurrencies {
      transactioncurrencies {
        isocurrencycode
        transactioncurrencyid
      }
    }
  `;

  const { $calculation } = store;

  when(
    () => $calculation.$options.getOptions('selectSupplierCurrency').length > 0,
    async () => {
      const {
        data: { transactioncurrencies },
      } = await apolloClient.query<GetTransactionCurrenciesQuery>({
        query: QUERY_GET_TRANSACTION_CURRENCIES,
      });

      const transactioncurrency_rub = transactioncurrencies?.find(
        (x) => x?.isocurrencycode === 'RUB'
      );
      if (transactioncurrency_rub) {
        $calculation
          .element('selectSupplierCurrency')
          .setValue(transactioncurrency_rub.transactioncurrencyid);
      }
    }
  );
}
