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

import { GET_API_SET } from '@/graphql/services/users/constants';

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

const query = `
  query ${GET_API_SET} {
    ${GET_API_SET} {
      resource
    }
  }
`;

const getResponse = ({ data }) => data[GET_API_SET].map(({ resource }) => resource);

export default (action$) =>
  action$.pipe(
    ofType(getApiSetAction.type),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
        variables: {},
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return of(
              setAction({
                apiSet: getResponse(response),
              }),
            );
          }

          return EMPTY;
        }),
      );

      return concat(
        of(
          setAction({
            apiSet: null,
          }),
        ),
        stream$,
      );
    }),
  );
