/* eslint-disable @typescript-eslint/naming-convention */
import { gql } from '@apollo/client';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import type * as CRMTypes from 'gql/crm.types';
import { autorun } from 'mobx';
import type { ReactionsContext } from 'process/types';

dayjs.extend(utc);

export default function computedReactions({ store, apolloClient }: ReactionsContext) {
  const QUERY_GET_EVO_CURRENCY_CHANGES = gql`
    query GetCurrencyChanges($currentDate: DateTime) {
      evo_currencychanges(statecode: 0, evo_coursedate_param: { eq: $currentDate }) {
        evo_currencychange
        evo_ref_transactioncurrency
      }
    }
  `;

  const QUERY_GET_CURRENCY_ISOCODE = gql`
    query GetCurrencyISOCode($id: Uuid!) {
      transactioncurrency(transactioncurrencyid: $id) {
        isocurrencycode
      }
    }
  `;

  const { $calculation } = store;

  autorun(
    async () => {
      const supplierCurrencyId = $calculation.element('selectSupplierCurrency').getValue();
      const leaseObjectPrice = $calculation.element('tbxLeaseObjectPrice').getValue();
      const supplierDiscountRub = $calculation.element('tbxSupplierDiscountRub').getValue();

      if (!supplierCurrencyId) {
        $calculation.$values.setValue('plPriceRub', leaseObjectPrice);
        $calculation.$values.setValue('discountRub', supplierDiscountRub);

        return;
      }

      const {
        data: { transactioncurrency },
      } = await apolloClient.query<
        CRMTypes.GetCurrencyIsoCodeQuery,
        CRMTypes.GetCurrencyIsoCodeQueryVariables
      >({
        query: QUERY_GET_CURRENCY_ISOCODE,
        variables: {
          id: supplierCurrencyId,
        },
      });

      if (transactioncurrency?.isocurrencycode === 'RUB') {
        $calculation.$values.setValue('plPriceRub', leaseObjectPrice);
        $calculation.$values.setValue('discountRub', supplierDiscountRub);

        return;
      }

      const {
        data: { evo_currencychanges },
      } = await apolloClient.query<
        CRMTypes.GetCurrencyChangesQuery,
        CRMTypes.GetCurrencyChangesQueryVariables
      >({
        query: QUERY_GET_EVO_CURRENCY_CHANGES,
        variables: {
          currentDate: dayjs().utc(false).format('YYYY-MM-DD'),
        },
      });

      const evo_currencychange = evo_currencychanges?.find(
        (x) => x?.evo_ref_transactioncurrency === supplierCurrencyId
      );

      $calculation.$values.setValue(
        'plPriceRub',
        leaseObjectPrice * (evo_currencychange?.evo_currencychange || 0)
      );

      $calculation.$values.setValue(
        'discountRub',
        supplierDiscountRub * (evo_currencychange?.evo_currencychange || 0)
      );
    },
    {
      delay: 100,
    }
  );
}
