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

import { getHubsAction, setHubsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';

const queryGQL = `
query hostedWatchHubs ($searchText: String, $watchId: Int) {
  hostedWatchHubs (searchText: $searchText, watchId: $watchId) {
    id
    name
  }
}`;

export default (action$) =>
  action$.pipe(
    ofType(getHubsAction.type),
    debounce(() => timer(500)),
    filter(() => !!getToken()),
    switchMap(({ payload: { searchText, watchId } }) =>
      gqlRequest({
        query: queryGQL,
        variables: {
          searchText,
          watchId,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          let hubs = [];

          if (!errors.length) {
            hubs = data.hostedWatchHubs.map(({ id, name }) => ({ id, title: name }));
          }

          return of(setHubsAction(hubs));
        }),
      ),
    ),
  );
