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

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

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

const query = `
  query getPlayerFeedsOptions(
    $pageSize: Int
    $searchText: String
    $publisherId: Int
    $includePublicContent: Int
  ) {
    getPlayerFeedsOptions(
      pageSize: $pageSize
      searchText: $searchText
      publisherId: $publisherId
      includePublicContent: $includePublicContent
    ) {
      records {
        id
        name
        description
        accountId
        contentOwner {
        id
        name
        isPublic
        }
       }
      recordsTotal
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getPlayerFeedsOptionsAction.type),
    debounce(({ payload }) => timer(payload.search?.length > 1 ? 1000 : 0)),
    switchMap(({ payload }) => {
      const actions = [];
      const stream$ = gqlRequest({
        query,
        variables: {
          searchText: payload.search ?? '',
          pageSize: ROWS_PER_PAGE_DEFAULT_FILTER,
          publisherId: payload.publisherId,
          includePublicContent: payload.includePublicContent,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            actions.push(
              of(
                setAction({
                  playerContentOwnerFeedsOptions: response.data.getPlayerFeedsOptions.records,
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );
      return concat(of(setPlayerIsLoadingAction(true)), stream$, of(setPlayerIsLoadingAction(false)));
    }),
  );
