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

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

const query = `
  query getAdServersPCNPlayerTypesOptions {
    getAdServersPCNPlayerTypesOptions {
      id
      name
    }
  }
`;

const getResponse = ({ data: { getAdServersPCNPlayerTypesOptions } }) => getAdServersPCNPlayerTypesOptions;

export default (action$) =>
  action$.pipe(
    ofType(getPlayerTypesOptionsAction.type),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            const playerTypesOptions = getResponse(response);

            actions.push(
              of(
                setAction({
                  playerTypesOptions,
                }),
              ),
            );
          }

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

      return concat(
        of(
          setAction({
            playerTypesOptions: [],
          }),
        ),
        stream$,
      );
    }),
  );
