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

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

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

const getResponse = ({ data: { getVideoUserHubs } }) =>
  getVideoUserHubs.records.map((record) => ({ value: `${record.id}`, label: record.name }));

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

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

          if (!response.errors.length) {
            const hubsOptions = getResponse(response);

            actions.push(of(setAction({ hubsOptions })));
          }

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

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