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

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

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

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

          if (!errors.length) {
            actions.push(
              of(setHubOptionsAction(data.playlistGetHubs.records.map(({ id, name }) => ({ value: id, label: name })))),
            );
          }

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

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