import { concat, Observable, of, timer } from 'rxjs';
import { debounce, filter, switchMap } from 'rxjs/operators';
import type { Action } from '@reduxjs/toolkit';

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

const query = `
  query analyticsAccountPlayers(
    $searchText: String
  ) {
    analyticsAccountPlayers(
      searchText: $searchText
    ) {
      id
      name
      alias
    }
  }
`;

export default (action$: Observable<Action>) =>
  action$.pipe(
    filter((action): action is ReturnType<typeof getPlayersAction> => action.type === getPlayersAction.type),
    debounce((action) => timer(action.payload ? 1000 : 0)),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          searchText: action.payload || undefined,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(
              of(
                setAction({
                  playersOptions:
                    data.analyticsAccountPlayers?.map((item: { alias: string; name: string }) => ({
                      label: item.alias,
                      value: item.name,
                    })) ?? [],
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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