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

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

const query = `
  query GetGeneralAnalyticsStatus {
    getGeneralAnalyticsStatus {
      overallFailure
      popup
      message 
    }
  }
`;

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

export default (action$) =>
  action$.pipe(
    ofType(getStatusAction.type),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const data = getResponse(response);

            return of(
              setFieldAction({
                statusOverallFailure: !!data.overallFailure,
                statusShowPopup: !!data.popup,
                statusPopupMessage: data.message,
              }),
            );
          }

          return EMPTY;
        }),
      );

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