import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { GET_SALESFORCE_DATA } from '@/graphql/services/accounts/constants';

import { PAYLOAD_NAME } from '@/graphql/services/accounts/types/payload/salesForce';

import * as selectors from '../selectors';
import { getSalesforceDataAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query ${GET_SALESFORCE_DATA}($payload: ${PAYLOAD_NAME}) {
    ${GET_SALESFORCE_DATA}(payload: $payload) {
      name
      salesManager
      accountManager
      accountManagerEmail
      type
      accountDashboards {
        general {
          id
          uiName
          enabled
          order
          tooltip {
            info
            link
            linkTitle
          }
        }
        custom {
          id
          uiName
          enabled
          order
          tooltip {
            info
            link
            linkTitle
          }
        }
      }
    }
  }
`;

const getResponse = ({ data }) => {
  const res = data[GET_SALESFORCE_DATA];

  return {
    ...res,
  };
};

export default (action$, state$) =>
  action$.pipe(
    ofType(getSalesforceDataAction.type),
    switchMap(() => {
      const salesforceId = selectors.salesforceIdSelector(state$.value);

      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            id: salesforceId,
          },
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            const { accountDashboards, ...data } = getResponse(response);

            const dashboardsGeneral = accountDashboards?.general?.sort((a, b) => a.order - b.order) || [];
            const dashboardsCustom = accountDashboards?.custom?.sort((a, b) => a.order - b.order) || [];

            actions.push(
              of(
                setAction({
                  ...data,
                  dashboardsGeneral,
                  dashboardsCustom,
                }),
              ),
            );
          }

          return concat(...actions);
        }),
      );

      return concat(
        of(setAction({ isSalesforceDataLoading: true })),
        stream$,
        of(setAction({ isSalesforceDataLoading: false })),
      );
    }),
  );
