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

import * as selectors from '../selectors';
import { getAccountsForWaterfallAction, setModalInfoAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getUserTimezoneSelector } from '@/modules/@common/user/redux/selectors';

export default (action$, state$) =>
  action$.pipe(
    ofType(getAccountsForWaterfallAction.type),
    debounce((action) => timer(action.payload?.name?.length ? 1000 : 0)),
    switchMap(({ payload: { name, config } }) => {
      const state = state$.value;

      const timezone = getUserTimezoneSelector(state);
      const filterByDate = selectors.filterByDateSelector(state);

      const { change, dimension, changeDimension, ...range } = filterByDate;
      let filters = {};

      if (dimension) {
        filters = {
          ...filters,
          dimension,
        };
      }

      if (change) {
        filters = {
          ...filters,
          changeRanges: [{ ...change, timezone }],
        };
      }

      if (changeDimension) {
        filters = {
          ...filters,
          changeDimension,
        };
      }

      let mainParams = {
        fields: config.fields,
        size: 30,
        from: 0,
        filters: {
          ranges: [
            {
              ...range,
              timezone,
            },
          ],
          ...filters,
        },
      };

      if (name?.length) {
        mainParams = {
          ...mainParams,
          filters: {
            ...mainParams.filters,
            query: name,
          },
        };
      }

      const stream$ = gqlRequest({
        query: config.accountsQuery,
        variables: {
          ...mainParams,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          let actions = [];

          const accountsData = {
            ...data.supplyAccountsData,
            ...data.demandAccountsData,
          };

          if (!errors.length) {
            actions = [
              of(
                setModalInfoAction({
                  accountsOptions: [...accountsData.data].filter((item) => !!item.name?.length),
                }),
              ),
            ];

            return concat(...actions);
          }

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

      return concat(stream$);
    }),
  );
