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

import { getHubsOptionsAction, setModuleStateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query GetUserRulesHubs(
    $pageSize: Int,
    $searchText: String,
    ) {
      getUserRulesHubs(
        pageSize: $pageSize,
        searchText: $searchText
      ) {
       id
       name
      }
  }
`;

const getResponse = ({ data: { getUserRulesHubs } }) =>
  getUserRulesHubs.map((record) => ({ label: record.name, value: record.id }));

export default (action$) =>
  action$.pipe(
    ofType(getHubsOptionsAction.type),
    switchMap((action) => {
      const variables = {
        pageSize: 30,
      };

      if (action.payload) {
        variables.searchText = action.payload;
      }

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

          if (!response.errors.length) {
            actions.push(
              of(
                setModuleStateAction({
                  hubsOptions: getResponse(response),
                }),
              ),
            );
          }

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

      return concat(
        of(
          setModuleStateAction({
            hubsOptions: null,
          }),
        ),
        stream$,
      );
    }),
  );
