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

import { getPlayersAction, setPlayersAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getPublisherIdsSelector } from '@/modules/@common/user/redux/selectors';

const queryGQL = `
  query getPublisherPlayers($publisherIds: [Int]) {
    getPublisherPlayers(publisherIds: $publisherIds) {
      results {
        id
        name
        alias
        publisherId
        urlPrefix
        displayEmbedCode
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getPlayersAction.type),
    filter((action) => action?.payload?.id || !!getPublisherIdsSelector(state$.value)?.length),
    switchMap((action) => {
      const variables = {};

      if (action.payload?.id) {
        variables.publisherIds = [action.payload.id];
      }

      const stream$ = gqlRequest({ query: queryGQL, variables }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];
          const players = data.getPublisherPlayers?.results.sort((a, b) => a?.alias?.localeCompare(b?.alias));

          if (!errors.length) {
            actions.push(of(setPlayersAction(players)));
          }

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

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