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

import { getHubOptionsAction, updateStoreByPropAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query WatchGetHubs(
    $pageSize: Int,
    $searchText: String,
  ) {
    watchGetHubs(
      pageSize: $pageSize,
      searchText: $searchText
    ) {
      records {
        id
        name
        slug
        accountId
      }
    }
  }
`;

const getResponse = ({
  data: {
    watchGetHubs: { records },
  },
}) => records.map((hub) => ({ value: hub.id, label: hub.name, accountId: hub.accountId, slug: hub.slug }));

export default (action$) =>
  action$.pipe(
    ofType(getHubOptionsAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          pageSize: 30,
          searchText: action.payload ?? '',
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

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

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

      return concat(
        of(
          updateStoreByPropAction({
            hubOptions: null,
          }),
        ),
        stream$,
      );
    }),
  );
