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

import { ROWS_PER_PAGE_DEFAULT_FILTER } from '@/modules/players/Players/constants';

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

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

const getResponse = ({ records }) =>
  records.map(({ id, name }) => ({
    value: id,
    label: name,
  }));

export default (action$) =>
  action$.pipe(
    ofType(getPublishersOptionsAction.type),
    debounce((action) => {
      const search = action.payload;
      return timer(search.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          searchText: action.payload ?? '',
          pageSize: ROWS_PER_PAGE_DEFAULT_FILTER,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return of(
              setAction({
                publishersOptions: getResponse(response.data.getPlayerPublishersOptions),
              }),
            );
          }
          return EMPTY;
        }),
      );
      return concat(stream$);
    }),
  );
