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

import { getPublishersAction, setPublishersAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

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

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

          if (!errors.length) {
            actions.push(of(setPublishersAction(data.playlistGetHubs.records)));
          }

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

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