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

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

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

export default (action$) =>
  action$.pipe(
    ofType(getPlayersAction.type),
    debounce((action) => timer(action.payload ? 1000 : 0)),
    switchMap((action) => {
      let requestParams = {};

      if (action.payload?.length) {
        requestParams = {
          searchText: action.payload,
        };
      }

      const stream$ = gqlRequest({
        query,
        variables: {
          ...requestParams,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

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

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