import type { DocumentNode } from '@apollo/client';
import { gql } from '@apollo/client';
import type { Elements } from 'Components/Calculation/config/map/values';
import { reaction } from 'mobx';
import type { ReactionsContext } from 'process/types';

export default function urlsReactions({ store, apolloClient }: ReactionsContext) {
  const { $calculation } = store;

  /**
   * При выборе Интереса, ЛС и Предложения скачиваем ссылку CRM
   */
  function makeLinkReaction(elementName: Elements, linkElementName: Elements, query: DocumentNode) {
    reaction(
      () => $calculation.element(elementName).getValue(),
      (id) => {
        if (!id) {
          $calculation.element(linkElementName).resetValue();

          return;
        }

        const timeoutId = setTimeout(() => {
          $calculation.$status.setStatus(linkElementName, 'Loading');
        }, 1200);

        apolloClient
          .query({
            query,
            variables: {
              id,
            },
          })
          .then(({ data }) => {
            clearTimeout(timeoutId);
            if (data.entity?.link) {
              $calculation.element(linkElementName).setValue(data.entity?.link);
            }
          })
          .catch(() => {
            clearTimeout(timeoutId);
            $calculation.element(linkElementName).resetValue();
          });
      }
    );
    reaction(
      () => $calculation.element(linkElementName).getValue(),
      (url) => {
        if (!url) {
          $calculation.element(linkElementName).block();
        } else {
          $calculation.element(linkElementName).unblock();
        }
      }
    );
  }

  const QUERY_GET_LEAD_URL = gql`
    query GetLeadUrl($id: Uuid!) {
      entity: lead(leadid: $id) {
        link
      }
    }
  `;
  makeLinkReaction('selectLead', 'linkLeadUrl', QUERY_GET_LEAD_URL);

  const QUERY_GET_OPPORTUNITY_URL = gql`
    query GetOpportunityUrl($id: Uuid!) {
      entity: opportunity(opportunityid: $id) {
        link
      }
    }
  `;
  makeLinkReaction('selectOpportunity', 'linkOpportunityUrl', QUERY_GET_OPPORTUNITY_URL);

  const QUERY_GET_QUOTE_URL = gql`
    query GetQuoteUrl($id: Uuid!) {
      entity: quote(quoteId: $id) {
        link
      }
    }
  `;
  makeLinkReaction('selectQuote', 'linkQuoteUrl', QUERY_GET_QUOTE_URL);
}
